我正在使用以下方法通过 SMTP 从 Python 发送邮件。这是正确的使用方法还是我遗漏了一些问题?
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
最佳答案
我使用的脚本非常相似;我在这里发布它作为如何使用 email.* 模块生成 MIME 消息的示例;所以这个脚本可以很容易地修改为附加图片等。
我依靠我的 ISP 添加日期时间 header 。
我的 ISP 要求我使用安全的 smtp 连接来发送邮件,我依赖 smtplib 模块(可在 http://www1.cs.columbia.edu/~db2501/ssmtplib.py 下载)
在您的脚本中,用于在 SMTP 服务器上进行身份验证的用户名和密码(下面给出虚拟值)在源代码中以纯文本形式显示。这是一个安全漏洞;但最好的选择取决于您需要(想要?)保护这些。
========================================
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
关于python - 使用 SMTP 从 Python 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64505/