Send an email in python - python

I am trying to send an email. The code I am using is found below:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email_user = 'email#gmail.com'
email_password = 'password'
email_send = 'receiver#gmail.com'
subject = 'subject'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Hi there, sending this email from Python!'
msg.attach(MIMEText(body,'plain'))
try:
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', port=587)
server.starttls()
server.login(email_user, email_password)
server.sendmail(email_user,email_send,text)
server.quit()
print('successfully sent the mail')
except:
print("failed to send mail")
I get an error "failed to send mail" with the error message:
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials t10sm6451859wra.16 - gsmtp')
The error occurs on the server.login() line, I am not able to login.
I checked other post and it says, it has to do with wrong credentials but my credentials are correct. I have check and double checked.
What could be the problem with this and how do I resolve it?

Send an email using python is easy, you may have encountered mistakes in your snippet code above and I am lazy to debug your code. But here might be the code you prefer.
The smtp.gmail.com,465 make your code secure. This snippet of code will send email to recipient through spam but lot number of emails you wish to send, will not be blocked by Gmail, you also can use bot to send email through recipient via this snippet of code.
Send Multiple Recipients
In the to line, just separate recipients by comma
to = [
'<recipient_email_address1>',
'<recipient_email_address2>',
'<recipient_email_address3>']
import smtplib
def sendEmailFunc():
gmail_user = '<your_sender_email_address_here>'
gmail_password = '<credential_password_of_above_email>'
sent_from = gmail_user
to = ['<recipient_email_address>']
subject = '<write_your_email_subject_here>'
body = "<write_your_email_body_here>"
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('====Email Sent Successfully====')
except:
print ('Something went wrong...')
NOTE
Please be careful with your indentation.
Hope this helpful for you.
Thank you.

Related

Send emal stmp office 365 : message empty

I'm trying to send an email in Python
It's working without problem with gmail with this code :
import smtplib
sender = 'xxx#xxx'
receivers = ['xxx#gmail.com']
message = "hello"
try:
smtpObj = smtplib.SMTP('smtp.gmail.com:587')
smtpObj.starttls()
smtpObj.login('xxxx#gmail.com', 'my_password')
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
print("okay")
except:
print("notokay")
But when i use it with office 365, the email is send but the message is empty.
It's the same code but with 'smtp.office365.com:587' with my correct login and password.
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('hello')
msg['Subject'] = 'Urgent message'
msg['From'] = 'xxx#xxx'
msg['To'] = 'xxx#gmail.com'
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login('xxx#gmail.com', 'my_password')
s.sendmail('xxx#xxx', 'xxx#gmail.com', msg.as_string())
s.quit()
Try the following, it might be because you need to create a MIMEText context for the formatting to be accepted by office365.

SMTP Sending e-mail issue with Gmail

I have a script that sends a .png file with SMTP. When I use a hotmail account;
smtplib.SMTP('smtp.live.com', 587)
It works without any problem. But when I use a gmail account;
smtplib.SMTP('smtp.gmail.com', 587)
An error raises: SMTPServerDisconnected: Connection unexpectedly closed
I've changed smtplib.SMTP('smtp.gmail.com', 587) to smtplib.SMTP('localhost') but didn't work. How can I fix this gmail problem?
Try this code,its working fine for me,
import smtplib
## email sending function
def email_sender(input_message, email_to, client):
''' function to send email '''
to = email_to
gmail_user = '' ## email of sender account
gmail_pwd = '' ## password of sender account
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' +'Subject:site down! \n'
input_message = input_message + client
msg = header + input_message
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
you can user smtplib and email for sending emails, this code working for me after i follow this steps.
steps are
Sign in to Gmail.
Click the gear in the top right .
Select Settings.
Click Forwarding and POP/IMAP.
Select Enable IMAP.
6.Click Save Changes
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "your email"
my_password = r"your password"
you = "to email id"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
part2 = MIMEText(html, 'html')
msg.attach(part2)
s = smtplib.SMTP_SSL('smtp.gmail.com')
s.login(me, my_password)
s.sendmail(me, you, msg.as_string())
print s
s.quit()

python: smtp with TLS delivers no message

I'm trying to send an email through the office365 server. The email is properly delivered, however the message is not attached
Assistance is most appreciated
import smtplib
to = "me#gmail.com"
office365_user = 'announcement#somewhere.com'
office365_pwd = 'password'
smtpserver = smtplib.SMTP("smtp.office365.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(office365_user,office365_pwd)
msg = "This is a test email \n"
smtpserver.sendmail(office365_user, to, msg)
smtpserver.close()
Your message is not a valid mail message, which consists of a header and a body. Try something like this:
msg = """From: <me#example.com>
To: <you#example.com>
Subject: foo
This is a test email
"""
Consider constructing the message in the same manner as the Python documentation.
from email.mime.text import MIMEText
msg = MIMEText("This is a test email")
msg['Subject'] = 'Email Subject'
msg['From'] = 'announcement#somewhere.com'
msg['To'] = 'me#gmail.com'
Also, I'm not sure about using smtpserver.close(). It seems the proper way is smtpserver.quit().

Sending e-mails using yahoo account in python

I have yahoo account.
Is there any python code to send email from my account ?
Yes, here is the code :
import smtplib
fromMy = 'yourMail#yahoo.com' # fun-fact: "from" is a keyword in python, you can't use it as variable.. did anyone check if this code even works?
to = 'SomeOne#Example.com'
subj='TheSubject'
date='2/1/2010'
message_text='Hello Or any thing you want to send'
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( fromMy, to, subj, date, message_text )
username = str('yourMail#yahoo.com')
password = str('yourPassWord')
try :
server = smtplib.SMTP("smtp.mail.yahoo.com",587)
server.login(username,password)
server.sendmail(fromMy, to,msg)
server.quit()
print 'ok the email has sent '
except :
print 'can\'t send the Email'
I racked my head (briefly) regarding using yahoo's smtp server. 465 just would not work. I decided to go the TLS route over port 587 and I was able to authenticate and send email.
import smtplib
from email.mime.text import MIMEText
SMTP_SERVER = "smtp.mail.yahoo.com"
SMTP_PORT = 587
SMTP_USERNAME = "username"
SMTP_PASSWORD = "password"
EMAIL_FROM = "fromaddress#yahoo.com"
EMAIL_TO = "toaddress#gmail.com"
EMAIL_SUBJECT = "REMINDER:"
co_msg = """
Hello, [username]! Just wanted to send a friendly appointment
reminder for your appointment:
[Company]
Where: [companyAddress]
Time: [appointmentTime]
Company URL: [companyUrl]
Change appointment?? Add Service??
change notification preference (text msg/email)
"""
def send_email():
msg = MIMEText(co_msg)
msg['Subject'] = EMAIL_SUBJECT + "Company - Service at appointmentTime"
msg['From'] = EMAIL_FROM
msg['To'] = EMAIL_TO
debuglevel = True
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.set_debuglevel(debuglevel)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
if __name__=='__main__':
send_email()
Visit yahoo account security page here
You'll need to generate an app password - it's an option towards the bottom of the screen. Use the password Yahoo generated on this page in your script.
To support non-ascii characters; you could use email package:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
# provide credentials
login = 'you#yahoo.com'
password = getpass('Password for "%s": ' % login)
# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ', '.join([login, ])
# send it
s = SMTP_SSL('smtp.mail.yahoo.com', timeout=10) #NOTE: no server cert. check
s.set_debuglevel(0)
try:
s.login(login, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
s.quit()
There are a couple of issues. One is addressed by an answer already posted.
Use TLS (Port 465)
Make sure you have an app password. Yahoo and other email services have updated their authentication practices to limit things that can login without 2 factor authentication. If you want to authenticate with smtplib you need to create an app password here: https://login.yahoo.com/myaccount/security/app-password
If you do that then you'll be able to send emails
For A good year and a half I had the following def working fine on PC's and Pi's. I had a script emailing me every Saturday at noon as a general health check. The working part was..
def my_callback():
server = smtplib.SMTP('smtp.mail.yahoo.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
The about two weeks ago its stopped working on all my devices. Running through the script I found that the "server.starttls()" line was the source of the failure. Investigating around I came to find that reverting to port 465 and SSL, dropping the server.starttls() fixed the Issue.
def my_callback():
server = smtplib.SMTP_SSL('smtp.mail.yahoo.com', 465)
server.login(username,password)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
Anybody else have this issue? Have Yahoo changed something?

Sending mail with python using gmail

I've tried sending mail with python from gmail and it works fine. But the problem is when I created the Mail class with one method to whom I send specific string from my code, it can't be send.
class Mail:
def send_mail(self, msg):
import smtplib
fromaddr = 'something#something.com'
toaddrs = 'something#gmail.com'
msg = msg + "something"
print msg
username = 'something'
password = 'something'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
This way it sends mail but the only thing in mail is "something" that I added to string, and print msg outputs the whole string plus "something". What could be the problem?
This is the whole class for now, and it's called
mail = Mail()
mail.send_mail(message)
I don't know what was the problem, but I managed to send it using MIME that's already in python
So here is the code that works:
def send_mail(self, message):
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
gmailUser = 'something#gmail.com'
gmailPassword = 'something'
recipient = 'something#something.com'
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = recipient
msg['Subject'] = "Subject"
msg.attach(MIMEText(message))
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
The problem is most likely that the content of the message seems to requite an extra line break between the addresses and the body of the message. The solution given by iblazevic is a much more readable way of doing it anyway though.

Categories

Resources