Python SMTPAuthnticationError [duplicate] - python

This question already has an answer here:
UnicodeEncodeError: 'ascii' codec can't encode character ... when sending email
(1 answer)
Closed 9 months ago.
Up until yesterday I had no issue sending emails with python and now for some reason I am getting the following error.
Traceback (most recent call last):
File "main.py", line 20, in <module>
mail(name)
File "/home/runner/mail.py", line 26, in mail
smtpserver.login(gmail_user, gmail_password)
File "/usr/local/lib/python3.7/smtplib.py", line 730, in login
raise last_exception
File "/usr/local/lib/python3.7/smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "/usr/local/lib/python3.7/smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
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 p17sm967082ils.71 - gsmtp')
I have been using the below code for about 4 months and haven't had any issues. Here is the code I am using to access gmail:
import smtplib
def mail(name):
gmail_user = 'email#gmail.com'
gmail_password = 'password'
emaillist = ['email#email.com']
for email in emaillist:
sent_from = gmail_user
to = email
subject = 'Subject'
body = "Body"
email_text = '''\
From: %s
To: %s
Subject: %s
%s
'''%(sent_from, 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, body)
server.close()
print('Email sent!')
except:
print('Oops!')
I have tried changing the use less secure apps in gmail, enabling IMAP, and changing the password for the email account. So far no luck with solving the issue. Any help would be greatly be appreciated.

Google has increased its security policies, I invite you to read this link in the part of: Less secure apps & your Google Account and open the link like bellow ( Less secure app access)
https://support.google.com/accounts/answer/6010255
later Allow access to unsafe applications: YES

Related

Not able to Send mail to Outlook.com via SMTP in Python

I am able to send the mail to gmail account via SMTP in Python. But when tried doing the same for Outlook - office365, it is throwing the error.
Code to send mail to gmail (working)
import smtplib
sender_email = "ABC#gmail.com"
rec_email = "ABC#gmail.com"
password = input(str("pwd:"))
message = "hey sent using python"
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(sender_email,password)
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email)
code for Outlook(throwing error)
import smtplib
sender_email = "ABC#companydomain.com"
rec_email = "ABC#companydomain.com"
password = input(str("pwd:"))
message = "hey sent using python"
server = smtplib.SMTP('smtp.outlook.com',587)
server.starttls()
server.login(sender_email,password)
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email )
The following error occurs when i run the above outlook code:
Traceback (most recent call last):
File "C:/Users/ABC/Python/Python37/pythonmail.py", line 32, in <module>
server.login(sender_email,password)
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 730, in login
raise last_exception
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "C:\Users\ABC\Python\Python37\lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.3 Authentication unsuccessful
[BM1PR01CA0154.INDPRD01.PROD.OUTLOOK.COM]')
i even went through the following links:
[https://stackoverflow.com/questions/57203843/unable-to-send-mail-in-python-on-outlook-with-the-smtplib][1]
[https://www.pythonanywhere.com/forums/topic/1961/][2]
[https://stackoverflow.com/questions/66061531/send-mail-from-alias-mail-id-using-python-smtplib][2]
Can somebody help me on how to fix the error??
Meanwhile the below code worked for both gmail and outlook using win32com.client. But i want to do it with SMTP lib. Kindly help
import win32com.client as client
outlook = client.Dispatch("Outlook.Application")
message = outlook.CreateItem(0)
message.Display()
message.To = 'ABC#domain.com'
message.subject = 'Test Mail'
message.body = 'Sending a test mail :)'
message.send
print("mail sent successfully")
Tried by not giving port number and password. It worked.
import smtplib
sender_email = "test_mail#company.com"
rec_email = ["ABC#company.com"]
message = "hey sent using python"
server = smtplib.SMTP('smtp.corp.company.com')
print("Login success")
server.sendmail(sender_email,rec_email, message)
print("Email sent to",rec_email )

Getting smtplib.SMTPAuthenticationError while sending email using python on pythonanywhere

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

Python script to send mail

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("******#gmail.com", "*******")
msg = "Hello!"
server.sendmail("rajesh.debugs#gmail.com", "rjucsm#gmail.com", msg)
OUTPUT :
C:\Users\Admin\PycharmProjects\Gabbar\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/Gabbar/MadhuBhai/t3.py
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/Gabbar/MadhuBhai/t3.py", line 5, in <module>
server.login("******#gmail.com", "******")
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 730, in login
raise last_exception
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtX\n5.7.14 HDzghr7H0UegF2rvoxWT6p9FwK8ct-IgZQXTa09qiineo743EE4PjOLOukbW-7fN2_FfIx\n5.7.14 qBwOghPCGmq1zlaUP3231EHWXgeut6dhRtiEjEVKAd-VKglbnUqvCyPMLKlADKhWt56L_5\n5.7.14 afzoYLGapj8SmZxp_W6VMrkj10aK9xthTsrmUerV9bkqgILAnKh9SWOO2n-7WsHO43reIf\n5.7.14 MQqmW0G2lyXQWbYt-8LxUHRt3ATI8> 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 v5-v6sm6337091pfd.1 - gsmtp')
Process finished with exit code 1
Possible duplicate of: SMTPAuthenticationError when sending mail using gmail and python
You will need to look at https://support.google.com/accounts/answer/6010255?hl=en and enable https://myaccount.google.com/lesssecureapps for your mail account.
If you aren't set on using with smtplib, then I would recommend SendGrid for sending emails (if you send < 100 emails/day then it's free).
import sendgrid
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey=sendgrid_api_key)
from_email = Email("test#example.com")
to_email = Email("test#example.com")
subject = "Sending with SendGrid is Fun"
content = Content("text/plain", "content")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
You need to use email.mime along with smtp. Try below:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import smtplib
strFrom = 'xyz.uvw#gmail.com'
strTo = ['efg.abc#gmail.com','hij.lmn#gmail.com']
attachment = '<path to attachment if any>'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'TEST'
msgRoot['From'] = strFrom
msgRoot['To'] = ", ".join(strTo)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
msgText = MIMEText('<b>Summary</b>', 'html')
msgAlternative.attach(msgText)
fp = open(attachment, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtp = smtplib.SMTP("YOUREMAILHOST", 25, timeout=120)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.close()

sent mail from python CGI - Error

I'm trying to send a mail with from cgi web console using email input field but it fails with below error in apache logs
Traceback (most recent call last):
File "/opt/apache-dba/cgi-bin/main.py", line 132, in <module>
mail()
File "/opt/apache-dba/cgi-bin/main.py", line 129, in mail
s.sendmail(me, you, msg.as_string())
File "/usr/lib64/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'xxx#adp.com/': (501, '5.1.3 Bad recipient address syntax')}
But I'm able to run the same code and able to receive the mail from python shell
Below is the code, this looks like when I run the code from cgi it is trying to convert mailid from 'xxx#adp.com' to 'xxx#adp.com/' resulting syntax error.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Emailid = xxx#gmail.com
Link='http://google.com'
def mail():
me = "GETS.INDIA.DDS.TAM#gmail.com"
you = str(Emailid)
msg = MIMEMultipart('alternative')
msg['Subject'] = "Upgrade Status Link"
msg['From'] = me
msg['To'] = you
text = '%s' % str(Link)
part1 = MIMEText(text, 'plain')
msg.attach(part1)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
mail()
any help will be greatly appreciated, Thank you
It looks like Emailid should be a string. Try surrounding your test email in quotes to make it a string.
Emailid = 'xxx#gmail.com'

Sending multiple emails with python

I'm trying to create a daemon which regularly sends me emails and I'm using the following snippet of code to do so.
import smtplib
from datetime import date
from email.mime.text import MIMEText
def send_email():
SMTP_PORT = 587
SMTP_SERVER = 'smtp.mail.com'
SMTP_USERNAME = 'EMAIL'
SMTP_PASSWORD = 'PASSWORD'
EMAIL_TO = ['email#hotmail.com']
EMAIL_FROM = 'EMAIL'
EMAIL_SUBJECT = 'Test!'
DATE_FORMAT = '%d/%m/%Y'
EMAIL_SPACE = ', '
DATA='Email Content'
msg = MIMEText(DATA)
msg['Subject'] = EMAIL_SUBJECT + ' %s' % (date.today().strftime(DATE_FORMAT))
msg['To'] = EMAIL_SPACE.join(EMAIL_TO)
msg['From'] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
However, after 5 emails, even though I've added the senders email to my contact list on outlook/hotmail, the daemon returns the following exception:
Sending email! 1/1
Traceback (most recent call last):
File "daemon.py", line 91, in <module>
send_email()
File "daemon.py", line 78, in send_email
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'email#hotmail.com': (550, 'Requested action not taken: mailbox unavailable\nFailure sending mail. Try again later')}
Can anyone advise on how to get around this? Does anyone know of an email service that has been tested which will allow more than 5 emails or how I configure the smtplib to not stop sending after 5 emails to the same address?
UPDATE: When I change the receiving email address from outlook to gmail (another one of my emails) - it returns the same exception even though I've sent no emails to the gmail SMTP server.

Categories

Resources