Hip*_*ppo -2 python email python-3.x
我没有使用python发送电子邮件的经验,并且我一直在做一些研究,看来您需要安装一些服务器。他们没有从一开始就说明如何做,我很困惑,有人可以告诉我怎么做吗?
我正在使用Windows 10和python 3.2.2
我是在python3.6.3中创建的,此后,我将代码重建为python3.2.6,但它可以工作。:)
首先,我们将导入标准Python库中的一些内容。
import smtplib
from getpass import getpass
from email.mime.text import MIMEText
Run Code Online (Sandbox Code Playgroud)
小费!如果要通过gmail发送电子邮件,则必须启用安全性较低的应用程序:https : //myaccount.google.com/lesssecureapps
我们必须发送电子邮件,以便:
sender = 'example_sender@gmail.com'
receiver = 'example_receiver@gmail.com'
content = """The receiver will see this message.
Best regards"""
msg = MIMEText(content)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Simple app script'
Run Code Online (Sandbox Code Playgroud)
小费!当然,您还可以使用以下方法从文件中读取内容:
Run Code Online (Sandbox Code Playgroud)with open('/path/to/your/file', 'r') as file: content = file.read()
现在,我们可以处理“魔术”服务器端。
小费!您可以在电子邮件设置中轻松找到的服务器名称。(“ IMAP / POP”页面)上有我发现的服务器列表:https : //www.arclab.com/en/kb/email/list-of-smtp-and-pop3-servers-mailserver-list。 html
gmail的解决方案,但您可以在任何服务器上使用:
smtp_server_name = 'smtp.gmail.com'
#port = '465' # for secure messages
port = '587' # for normal messages
Run Code Online (Sandbox Code Playgroud)
小费!对于这些端口的区别,有一些答案: 端口465和587有什么区别?
我认为这段代码示例很简单。通过smtplib.SMTP_SSL,我们只能通过安全端口(465)处理服务器。在其他情况下,我们使用不同的方法。
if port == '465':
server = smtplib.SMTP_SSL('{}:{}'.format(smtp_server_name, port))
else :
server = smtplib.SMTP('{}:{}'.format(smtp_server_name, port))
server.starttls() # this is for secure reason
server.login(sender, getpass(prompt="Email Password: "))
server.send_message(msg)
server.quit()
Run Code Online (Sandbox Code Playgroud)
当服务器要登录时,您必须在shell中的提示符后键入密码。
就是这样。我从命令行在Linux上运行了它。
请随时提出问题!:)
PS。我在Windows 7上全新安装的python 3.2.2上对其进行了测试。一切正常。
归档时间: |
|
查看次数: |
4738 次 |
最近记录: |