Python学习:SMTP发送邮件(html)和带有附件的邮件

如果要发送html,就可以这样…

msg = MIMEText('<html><body><h1>Hello</h1>' +
    '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
    '</body></html>', 'html', 'utf-8')

下面是发送带有附件的

from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import parseaddr, formataddr
from email import encoders
import smtplib

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


msg =  MIMEMultipart()
msg['From'] = _format_addr('彭羿博<[email protected]>')
msg['To'] = _format_addr('[email protected]')
msg['Subject'] = Header('来自SMTP').encode()
msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
with open(r'C:\Users\admin\Desktop\test.png', 'rb') as f:
    # 设置附件的MIME和文件名,这里是png类型:
    mime = MIMEBase('image', 'png', filename='test.png')
    # 加上必要的头信息:
    mime.add_header('Content-Disposition', 'attachment', filename='test.png')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    # 把附件的内容读进来:
    mime.set_payload(f.read())
    # 用Base64编码:
    encoders.encode_base64(mime)
    # 添加到MIMEMultipart:
    msg.attach(mime)
from_addr = '[email protected]'#input('From: ')
password = '199312183434ppdx'#input('Password: ')
# 输入收件人地址:
to_addr = '[email protected]'#input('To: ')
# 输入SMTP服务器地址:
smtp_server = 'smtp.163.com'#input('SMTP server: ')
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_addr, password)
print(_format_addr('彭羿博<[email protected]>'))
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

在这部分代码里面,如果我直接使用header去对汉字解码就会出错,修改为只对名字进行header解码就不会出错…原因暂时不懂.

你可能感兴趣的:(Python学习:SMTP发送邮件(html)和带有附件的邮件)