Getting smtplib.SMTPAuthenticationError while sending email using python on pythonanywhere - python

I created a python script that sends emails using python and deployed it on pythonanywhere.
Here's the code:
import smtplib
import csv
import time
from string import Template
email_address = 'youremail#gmail.com'
email_password = 'password'
def send_emails(email_address,email_password):
while True:
with open('quotesource.txt','r') as f:
quotes = f.read()
daily_quote_num= 0
for quote in quotes.splitlines():
view_quote = quote
# opening user database
with open('database.csv', 'r') as csv_database:
database_reader = csv.reader(csv_database)
# looping through user database
for database_info in database_reader:
user_name = database_info[0]
user_email = database_info[1]
# sending email
t = Template('subject:Daily Quotes $num \n\n $quoteline\n \n Have a nice day $name !')
msg = t.substitute(num=daily_quote_num,quoteline= view_quote,name=user_name)
try:
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login(email_address, email_password)
smtp.sendmail(from_addr=email_address,to_addrs=user_email,msg=msg.encode('utf-8'))
smtp.quit()
except Exception as err:
raise(err)
daily_quote_num += 1
time.sleep(86400)
print(send_emails(email_address,email_password))
But when I run my code(by the way I am using python 3) I get this error:
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv\n5.7.14 KAMZ41q6khk64CjUNQU3xj
Bf4hohSdLujNyleDpsFQuzmwNAkIot0BkfdcE9DyK1gFpTh\n5.7.14 H-XuJMMPxDQnGiXrF0uRO4Z46iK1suCIM9hC5VUU5i5Rgdm09Wf6gnVloK_Rowff>\n5.7.14 Please log in via
your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 g136sm23063683qke.82 - gsmtp')
I have enabled less secure app feature and also IMAP on my gmail account and the code runs fine on my local computer but gets this error while running on python anywhere

Related

Python sending email script not getting credentials from external file

import smtplib
import os
import time
def send_email(contacts):
try:
user= passw=""
with open("credentials.txt", "r") as f:
file = f.readlines()
user = file[0].strip()
passw = file[1].strip()
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls() # it is necessary to start this before login
server.login(user, passw) # login credentials
subject = "Assignment Task for Working student job"
msg = "This is a msg body of assignment. "
message = 'Subject: {}\n\n{}'.format(subject, msg)
for i in contacts:
server.sendmail(user, contacts, message)
print(f"successfully sent email to {i} and wait for 10 seconds" )
time.sleep(10)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
if __name__ == "__main__":
#sender, password = read_creds()
contacts = ['editorawais#gmail.com', 'editorawais#yahoo.com', 'editorawais#live.com','techwpblog#gmail.com']
send_email(contacts)
I created this email script. But now i am getting error on login. My credentials.txt is just of two lines.
"Email address"
"Password"
Please can anybody help me where i am missing something. And the correct way possibly. Thanks
Lose the quotation marks if you indeed have those in the txt file. Python will try to plug in everything on the first and second line including the "" try just doing this in your .txt file.
email
password

I want to send email using google smtp server. But it always showing SMTPAuthenticationError

I want to send a mail after reading a specific a row from a excel file. I did as per rules i got on web. But my code is not working rather showing "smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s13sm4935540pfm.12 - gsmtp'" error. I have gone through multiple solution but none has worked in the end.
server.connect("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
password = input("Type your password and press enter: ")
print(type(password))
X = "from#gmail.com"
Y = "to#gmail.com"
server.login(X, password)
df = pd.read_excel(r'D:/Topu/files/Allocation.xlsx')
fc = df.iloc[:, 0]
try:
server.sendmail(X, Y, fc)
server.close()
except:
print("failed")
Login to your gmail account and enable the 'Allow less secure apps' to this link that will fix this. https://myaccount.google.com/lesssecureapps?pli=1

SMTP works in Linux but not on Mac [duplicate]

I am trying to send email (Gmail) using python, but I am getting following error.
Traceback (most recent call last):
File "emailSend.py", line 14, in <module>
server.login(username,password)
File "/usr/lib/python2.5/smtplib.py", line 554, in login
raise SMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
The Python script is the following.
import smtplib
fromaddr = 'user_me#gmail.com'
toaddrs = 'user_you#gmail.com'
msg = 'Why,Oh why!'
username = 'user_me#gmail.com'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
def send_email(user, pwd, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if isinstance(recipient, list) else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
if you want to use Port 465 you have to create an SMTP_SSL object:
# SMTP_SSL Example
server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server_ssl.ehlo() # optional, called by login()
server_ssl.login(gmail_user, gmail_pwd)
# ssl server doesn't support or need tls, so don't call server_ssl.starttls()
server_ssl.sendmail(FROM, TO, message)
#server_ssl.quit()
server_ssl.close()
print 'successfully sent the mail'
You need to say EHLO before just running straight into STARTTLS:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
Also you should really create From:, To: and Subject: message headers, separated from the message body by a blank line and use CRLF as EOL markers.
E.g.
msg = "\r\n".join([
"From: user_me#gmail.com",
"To: user_you#gmail.com",
"Subject: Just a message",
"",
"Why, oh why"
])
Note:
In order for this to work you need to enable "Allow less secure apps" option in your gmail account configuration. Otherwise you will get a "critical security alert" when gmail detects that a non-Google apps is trying to login your account.
I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:
https://support.google.com/accounts/answer/6010255
In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:
https://www.google.com/settings/security/lesssecureapps
Once that is set (see my screenshot below), it should work.
Login now works:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('me#gmail.com', 'me_pass')
Response after change:
(235, '2.7.0 Accepted')
Response prior:
smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')
Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:
https://accounts.google.com/DisplayUnlockCaptcha
Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.
UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:
235 == 'Authentication successful'
503 == 'Error: already authenticated'
The message says to use the browser to sign in:
SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')
After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.
This Works
Create Gmail APP Password!
After you create that then create a file called sendgmail.py
Then add this code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Created By : Jeromie Kirchoff
# Created Date: Mon Aug 02 17:46:00 PDT 2018
# =============================================================================
# Imports
# =============================================================================
import smtplib
# =============================================================================
# SET EMAIL LOGIN REQUIREMENTS
# =============================================================================
gmail_user = 'THEFROM#gmail.com'
gmail_app_password = 'YOUR-GOOGLE-APPLICATION-PASSWORD!!!!'
# =============================================================================
# SET THE INFO ABOUT THE SAID EMAIL
# =============================================================================
sent_from = gmail_user
sent_to = ['THE-TO#gmail.com', 'THE-TO#gmail.com']
sent_subject = "Hey Friends!"
sent_body = ("Hey, what's up? friend!\n\n"
"I hope you have been well!\n"
"\n"
"Cheers,\n"
"Jay\n")
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(sent_to), sent_subject, sent_body)
# =============================================================================
# SEND EMAIL OR DIE TRYING!!!
# Details: http://www.samlogic.net/articles/smtp-commands-reference.htm
# =============================================================================
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_app_password)
server.sendmail(sent_from, sent_to, email_text)
server.close()
print('Email sent!')
except Exception as exception:
print("Error: %s!\n\n" % exception)
So, if you are successful, will see an image like this:
I tested by sending an email from and to myself.
Note: I have 2-Step Verification enabled on my account. App Password works with this! (for gmail smtp setup, you must go to https://support.google.com/accounts/answer/185833?hl=en and follow the below steps)
This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.
Clarification
Navigate to https://myaccount.google.com/apppasswords and create an APP Password as stated above.
You down with OOP?
#!/usr/bin/env python
import smtplib
class Gmail(object):
def __init__(self, email, password):
self.email = email
self.password = password
self.server = 'smtp.gmail.com'
self.port = 587
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls()
session.ehlo
session.login(self.email, self.password)
self.session = session
def send_message(self, subject, body):
''' This must be removed '''
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.email,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.email,
headers + "\r\n\r\n" + body)
gm = Gmail('Your Email', 'Password')
gm.send_message('Subject', 'Message')
Here is a Gmail API example. Although more complicated, this is the only method I found that works in 2019. This example was taken and modified from:
https://developers.google.com/gmail/api/guides/sending
You'll need create a project with Google's API interfaces through their website. Next you'll need to enable the GMAIL API for your app. Create credentials and then download those creds, save it as credentials.json.
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
#pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send']
def create_message(sender, to, subject, msg):
message = MIMEText(msg)
message['to'] = to
message['from'] = sender
message['subject'] = subject
# Base 64 encode
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
return {'raw': b64_string}
#return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send_message(service, user_id, message):
#try:
message = (service.users().messages().send(userId=user_id, body=message).execute())
print( 'Message Id: %s' % message['id'] )
return message
#except errors.HttpError, error:print( 'An error occurred: %s' % error )
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
# Example read operation
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
# Example write
msg = create_message("from#gmail.com", "to#gmail.com", "Subject", "Msg")
send_message( service, 'me', msg)
if __name__ == '__main__':
main()
Not directly related but still worth pointing out is that my package tries to make sending gmail messages really quick and painless. It also tries to maintain a list of errors and tries to point to the solution immediately.
It would literally only need this code to do exactly what you wrote:
import yagmail
yag = yagmail.SMTP('user_me#gmail.com')
yag.send('user_you#gmail.com', 'Why,Oh why!')
Or a one liner:
yagmail.SMTP('user_me#gmail.com').send('user_you#gmail.com', 'Why,Oh why!')
For the package/installation please look at git or pip, available for both Python 2 and 3.
You can find it here: http://jayrambhia.com/blog/send-emails-using-python
smtp_host = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP()
server.connect(smtp_host,smtp_port)
server.ehlo()
server.starttls()
server.login(user,passw)
fromaddr = raw_input('Send mail by the name of: ')
tolist = raw_input('To: ').split()
sub = raw_input('Subject: ')
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = email.Utils.COMMASPACE.join(tolist)
msg['Subject'] = sub
msg.attach(MIMEText(raw_input('Body: ')))
msg.attach(MIMEText('\nsent via python', 'plain'))
server.sendmail(user,tolist,msg.as_string())
Dec, 2022 Update:
You need to use an app password to allow your app to access your google account.
Sign in with App Passwords:
An App Password is a 16-digit passcode that gives a less secure app or
device permission to access your Google Account. App Passwords can
only be used with accounts that have 2-Step Verification turned on.
In addition, google hasn't allowed your app to access your google account with username(email address) and password since May 30, 2022. So now, you need username(email address) and an app password to access your google account.
Less secure apps & your Google Account:
To help keep your account secure, from May 30, 2022, ​​Google no
longer supports the use of third-party apps or devices which ask you
to sign in to your Google Account using only your username and
password.
How to generate an app password:
First, click on Account from 9 dots:
Then, click on App passwords from Security. *Don't forget to turn on 2-Step Verification before generating an app password otherwise you cannot generate an app password:
Then, click on Other (Custom name):
Then, put your app name, then click on GENERATE:
Finally, you could generate the app password xylnudjdiwpojwzm:
So, your code with the app password above is as shown below:
import smtplib
fromaddr = 'user_me#gmail.com'
toaddrs = 'user_you#gmail.com'
msg = 'Why,Oh why!'
username = 'user_me#gmail.com'
password = 'xylnudjdiwpojwzm' # Here
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
In addition, settings.py with the app password above in Django is as shown below:
# "settings.py"
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myaccount#gmail.com'
EMAIL_HOST_PASSWORD = 'xylnudjdiwpojwzm' # Here
Realized how painful many of the things are with sending emails via Python thus I made an extensive library for it. It also has Gmail pre-configured (so you don't have to remember Gmail's host and port):
from redmail import gmail
gmail.user_name = "you#gmail.com"
gmail.password = "<YOUR APPLICATION PASSWORD>"
# Send an email
gmail.send(
subject="An example email",
receivers=["recipient#example.com"],
text="Hi, this is text body.",
html="<h1>Hi, this is HTML body.</h1>"
)
Of course you need to configure your Gmail account (don't worry, it's simple):
Set up 2-step-verification (if not yet set up)
Create an Application password
Put the Application password to the gmail object and done!
Red Mail is actually pretty extensive (include attachments, embed images, send with cc and bcc, template with Jinja etc.) and should hopefully be all you need from an email sender. It is also well tested and documented. I hope you find it useful.
To install:
pip install redmail
Documentation: https://red-mail.readthedocs.io/en/latest/
Source code: https://github.com/Miksus/red-mail
Note that Gmail don't allow changing the sender. The sender address is always you.
Enable less secure apps on your gmail account and use (Python>=3.6):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
gmailUser = 'XXXXX#gmail.com'
gmailPassword = 'XXXXX'
recipient = 'XXXXX#gmail.com'
message = f"""
Type your message here...
"""
msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Subject here..."
msg.attach(MIMEText(message))
try:
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()
print ('Email sent!')
except:
print ('Something went wrong...')
There is a gmail API now, which lets you send email, read email and create drafts via REST.
Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.
Of course, email should be handed off to a non-webserver queue, but it's nice to have options.
It's easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.
Here is a gist demonstrating it:
https://gist.github.com/timrichardson/1154e29174926e462b7a
great answer from #David, here is for Python 3 without the generic try-except:
def send_email(user, password, recipient, subject, body):
gmail_user = user
gmail_pwd = password
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
Seems like problem of the old smtplib. In python2.7 everything works fine.
Update: Yep, server.ehlo() also could help.
import smtplib
fromadd='from#gmail.com'
toadd='send#gmail.com'
msg='''hi,how r u'''
username='abc#gmail.com'
passwd='password'
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,passwd)
server.sendmail(fromadd,toadd,msg)
print("Mail Send Successfully")
server.quit()
except:
print("Error:unable to send mail")
NOTE:https://www.google.com/settings/security/lesssecureapps that should be enabled
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("fromaddress", "password")
msg = "HI!"
server.sendmail("fromaddress", "receiveraddress", msg)
server.quit()

Zapier and Pythoneverywhere smtp issues

I've been using Zapier and Pythoneverywhere for some backend stuff using Python, and recently I've been getting a 534 error as follows:
File "/usr/lib64/python2.7/smtplib.py", line 622, in login raise SMTPAuthenticationError(code, resp) SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbuE\n5.7.14 VyQLZTijmufE25PUD9vfTLC3FrnAU5nlNWptaIGEMv5N2OJ6SeJr1k1LxC0yuXv1eZAMYw\n5.7.14 ejmvetuDKIBX3L9MYPGLY75EUlIuSiSHEmp-0wpi6gazhumwltHXV07K9Q0lou0t4ky1QN\n5.7.14 7jnbEIhA1W6ceSVqvdwtH7wAOKsUhDlwYhkd3-81UClaoJ7sWRCICCJJW4iQxpIDNE4Yqr\n5.7.14 Tto1BfHEYh77B5bZkRiu5BxvjOfCY> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 t1sm124763qtt.25 - gsmtp'"
I'm pretty sure it isn't an issue with the code, because I've been using it for months. I'll post some test code for good measure, but really I'm wondering if anyone else has been getting the error and if they have figured out a solution.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
company = 'daves burgers'
dealtype = '409a'
analyst = 'Nate'
itemId = '92081920'
salesRep = 'shawn olsen'
companyLink = 'html link to company'
analystFirst = (analyst.split(' ',2))[0]
salesRepFirst = (salesRep.split(' ',2))[0]
contactEmail = 'contact#sana.com'
analystEmail = "analyst#gmail.com"
emailPass = "password"
html = """<html>A bunch of html></html>"""
fromaddr = analystEmail
bcc = ['bcc#bcc.com']
firstName= 'dave'
msg = MIMEMultipart()
msg['From'] = analyst
msg['Subject'] ="Scalar - "+company+" - "+dealtype+" - onboarding"
body = "Thanks "+salesRepFirst+".\n\n"+firstName+",\n\nPleased to e-meet you. We're looking forward to working on your valuation! To begin the onboarding process, please follow this link (link to onboarding "+companyLink+"/"+itemId+") to our onboarding platform, where you will be asked to verify information about your company as well as provide the necessary documentation for the valuation to begin. Should any questions arise while you're gathering the necessary docs, please reach out to me.\n\nOnce we receive the docs, we'll get started right away and will turn around the draft within 5-7 business days. We'll most likely want to set up a call with you once we've started the analysis. I'll reach out to you at that point.\n\nThanks!"
msg['To'] = contactEmail
toaddr = contactEmail
toaddrs = [toaddr] + bcc
msg.attach(MIMEText(body, 'plain'))
msg.attach(MIMEText(html,'html'))
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(analystEmail,emailPass)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
This error occurs no matter which email account I login to from Zapier or Pythonanywhere (Also, worth noting is that all the accounts have "less secure apps" allowed in the settings).
I'm not sure why this fixed it, but I made one change to this section of the code:
server.ehlo()
server.starttls()
And changed it to be:
server.ehlo()
server.starttls()
server.ehlo()
As per this (Error Sending Email (Gmail) Via Python 2.6) forum post.

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?

Categories

Resources