I am trying to send an automated email using python. The login details I am using are correct as it is running fine in local system. I have enabled IMAP and/or POP3. Also, enabled "Allow less secure apps" However, when I run it on the server, it gives the following error.
Traceback (most recent call last):
File "/home/memids/public_html/Python_Scripts/mail_test.py", line 126, in <module>
server.login(username,password)
File "/usr/local/lib/python3.9/smtplib.py", line 745, in login
raise last_exception
File "/usr/local/lib/python3.9/smtplib.py", line 734, in login
(code, resp) = self.auth(
File "/usr/local/lib/python3.9/smtplib.py", line 657, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'Incorrect authentication data')
The code I am using is given below-
#####
emailfrom = "***********"
emailto="******"
fileToSend = latest_name
username = "*********"
password = "*********"
rec=','.join(emailto)
msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = rec
msg["Subject"] = "Machine Output Demand Forecast for "+ now.strftime("%B")
msg.preamble = "Machine Output Demand Forecast"
t=now+timedelta(days=1)
t=t.strftime("%dth %b")
body = "Dear Team,PFA the Machine Output Demand Forecast for "+ t +"."
ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
if maintype == "text":
fp = open(fileToSend)
# Note: we should handle calculating the charset
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(fileToSend, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)
msg.attach(MIMEText(body, "plain"))
server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()