I am trying to learn how to send an email using python. All the tutorials on the web that I have read explain how to do it using Gmail.
But, from 30/05/2022 (despite the fact that everybody is free to do whatever he wants with his account) Google has a new policy that states:
To help keep your account secure, starting May 30, 2022, Google will no longer support the use of third-party apps or devices that only ask for your username and password for you. Sign in to your Google account.
Source: https://support.google.com/accounts/answer/6010255
And we get:
So my question is there any other way to send an email using python, (including email accounts belonging to an other company)?
Here is my function to send an email:
def send_email_fct(filename, filepath, fromaddr, mdpfrom, toaddr):
"""" filename: file name to be sent with extension
filepath: file path of the file to be sent
fromaddr: sender email address
mdpfrom: password of sender email address
toaddr: receiver email address"""
msg = MIMEMultipart() # instance of MIMEMultipart
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "data file"
body_email = "Body_of_the_mail"
msg.attach(MIMEText(body_email, 'plain'))
attachment = open(filepath, 'rb') # open the file to be sent
p = MIMEBase('application', 'octet-stream') # instance of MIMEBase
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(p) # attach the instance 'p' to instance 'msg'
s = smtplib.SMTP('smtp.gmail.com', 587) # SMTP
s.starttls()
s.login(fromaddr, mdpfrom)
text = msg.as_string()
s.sendmail(from_email_addr, toaddr, text) # sending the email
s.quit() # terminating the session
And I get this error:
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 c12-20020aa7d60c000000b0042be14040c1sm2612116edr.86 - gsmtp')
To fix this problem, I think that the only line that need to be change is this one:
s = smtplib.SMTP('smtp.gmail.com', 587)
If you know by what I can change it or if you see any other error, it will help me a lot! :-)
Here is a more precise answer with all the main steps. I hope it will help other people.
Log in into your email account: https://myaccount.google.com
Then go to the security part
Be sure that you have turn on two steps verification and click on "App password." As of 9th July 2023, this might not be visible, but is reachable directly via myaccount.google.com/apppasswords
Hope it will help other people!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With