下面的代码是用python的stmp的协议进行发送邮件
from email.mime.text import MIMEText
msg = MIMEText('hello, send by Python', 'plain', 'utf-8')
msg['From'] = 'Tim<[email protected]>'
msg['To'] = "[email protected]"
from_addr = '[email protected]'#input('From: ')
password = 'xxxxxxx'#input('Password: ')
# 输入收件人地址:
to_addr = '[email protected]'#input('To: ')
# 输入SMTP服务器地址:
smtp_server = 'smtp.163.com'#input('SMTP server: ')
import smtplib
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
开始没有初始化msg['From'],msg['To']
,导致出现错误554,邮件头是必须发的.
The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for a To or Cc header. If the first element of pair is false, then the second element is returned unmodified.
Optional charset is the character set that will be used in the RFC 2047 encoding of the realname if the realname contains non-ASCII characters. Can be an instance of str or a Charset. Defaults to utf-8.
这是parseaddr的文档描述:
Parse address – which should be the value of some address-containing field such as To or Cc – into its constituent realname and email address parts. Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned.
用来解析字符串中email的地址.
=========================================================
msg = MIMEText('hello, send by Python', 'plain', 'utf-8')
msg['From'] = Header('彭YYY<[email protected]>')
msg['To'] = Header('xxxxxxx@qq.com')
msg['Subject'] = Header('来自SMTP')
msg = MIMEText('hello, send by Python', 'plain', 'utf-8')
msg['From'] = Header('彭羿博<[email protected]>').encode()
msg['To'] = Header('634077956@qq.com').encode()
msg['Subject'] = Header('来自SMTP').encode()
>>> type(Header('和').encode())
<class 'str'>
encode的结果是一个str,这个和平常的encode的结果是byte是不一样的,暂时还没有搞清楚为什么要这样.
但是网上的例子是这样用的:
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
总之,现在可以发送一个含有中文,且格式较为标准的邮件了