所以我用Ubuntu建立了一个GCP VM,从那里我想通过我的邮件提供程序用python脚本发送常规报告。smtp端口是587,据我所知,该端口以前在GCP环境中是关闭的,但现在应该是可用的。
我的脚本是这样的:
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import time
timestr = time.strftime('(%Y-%m-%d)')
username='me@mydomain.de'
password='secretpw'
send_from = 'me@mydomain.de'
send_to = 'recipient@herdomain.com'
body = 'hello'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = 'important email'
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.ionos.de')
port = '587'
smtp = smtplib.SMTP('smtp.ionos.de')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(','), msg.as_string())
smtp.quit()
在执行时,机器需要一段时间才能输出超时:
Traceback (most recent call last):
File "test.py", line 25, in <module>
server = smtplib.SMTP('smtp.ionos.de')
File "/usr/lib/python3.8/smtplib.py", line 255, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.8/smtplib.py", line 339, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.8/smtplib.py", line 310, in _get_socket
return socket.create_connection((host, port), timeout,
File "/usr/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out
我可以,但是,ping smtp.ionos.de
和telnet smtp.ionos.de 587
形成cl与工作ping和连接的结果。
我也尝试了其他电子邮件提供商,包括gmail,并被困在完全相同的结果。
有人知道吗?谢谢你的帮助。
你的代码有多个问题:
- 连接服务器两次。
- 连接 时未指定端口号
- 未为加密创建SSL上下文。
在您的代码中,替换这些行:
server = smtplib.SMTP('smtp.ionos.de')
port = '587'
smtp = smtplib.SMTP('smtp.ionos.de')
smtp.ehlo()
smtp.starttls()
:
context = ssl.create_default_context()
smtp = smtplib.SMTP('smtp.ionos.de', 587)
smtp.ehlo()
smtp.starttls(context=context)
下面是一个使用GCP云功能测试的完整示例。在requirements.txt中不需要任何库。它使用Python 3.9。代码使用App Password,因为普通用户需要2FA。
import smtplib
import ssl
def send_email(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
"""
gmail_user = 'user@gmail.com'
gmail_password = 'YOURPASSWORD'
sent_from = gmail_user
to = ['foo@bar.com']
subject = 'Test e-mail from Python'
body = 'Test e-mail body'
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
context = ssl.create_default_context()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls(context=context)
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, body)
server.close()
print('Email sent (print)!')
return f'Email sent (return)!'