I am developing a simple system for obtaining stock information and sending it to me by email. The problem is occurring with the function that should send the email.
I'm trying to use Gmail to do this and it works on my machine, but when it runs on the Google Cloud Function instance, an error is generated. The error says:
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 DI7EWTXsfkIgcqDF1iU9gzO45O2rHEDek8EzvslcMMuOLXixqGFX_YhwsIz9P9OsZkRDf\n5.7.14 F7fWu8KmILP4m54Yb925Tl93FSuXLCUiWn7REseAjcak7RpZ_2tgWliAGFufsPSW>\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 b18sm13789218iln.46 - gsmtp')
And here is my simple code
import smtplib, ssl, os, sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
SMTP_SERVER = os.getenv('SMTP_SERVER', 'smtp.gmail.com')
SMTP_PORT = os.getenv('SMTP_PORT', 587)
EMAIL_USER = os.getenv('EMAIL_USER')
EMAIL_PASSWORD = os.getenv('EMAIL_PASSWORD')
def send_mail(email_from, to, subject, body_message, from_name=None):
from_str = '{} <{}>'.format(from_name, email_from) if not from_name is None else email_from
msg = MIMEMultipart()
msg['From'] = from_str
msg['To'] = to
msg['Subject'] = subject
body_html = body_message
msg.attach(MIMEText(body_html, 'html'))
text = msg.as_string()
server = smtplib.SMTP(SMTP_SERVER,SMTP_PORT)
server.ehlo() # Can be omitted
server.starttls()
server.ehlo() # Can be omitted
server.login(EMAIL_USER, EMAIL_PASSWORD)
server.sendmail(email_from, to, text)
server.quit()
The above function works perfectly on my machine. I already enabled insecure apps on this account.
I saw a post here that was talking about something like that. At one point in the post you can find the quote below.
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
So, this is the error that I'm getting but I don't know how to solve it inside of a Cloud Function.
Here is the link to the full discussion: Login credentials not working with Gmail SMTP