Python学习:stmp发送邮件(1)

下面的代码是用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,邮件头是必须发的.

[2]:如果邮件头里面含有中文就不能直接传入一个字符串了,网上demo使用formataddr,parseaddr和header来格式化:

这是formataddr的文档描述,

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的地址.

=========================================================

经过测试大概对这几个函数和类有了一个了解,Header(‘xxx’)负责把一个含有非ASCII字符的str转换成一个Header对象,如果直接把这个对象assign给msg也是可以发送的:

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')

但是把Header对象调用encode也可以发送:

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()

我个人的猜测是python会自动将header对象变成header.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))

用_format_addr来处理地址,我觉得有点奇怪,因为直接用Header也可以处理msf[‘From’]中含有中文的问题.forataddr似乎是把两个字符串拼接起来中间,将地址用<>括起来,这样做似乎可以让地址不用进行编码,可以保持字符串的格式,但是具体有什么好处暂时不知道.

总之,现在可以发送一个含有中文,且格式较为标准的邮件了

你可能感兴趣的:(Python学习:stmp发送邮件(1))