python Email功能:
- 发送普通文本邮件
- 发送带有html格式的邮件
- 发送带有附件的邮件
- 发送插入图片到正文的邮件
注: 这里由于使用的认证邮箱,所以省去了发送邮箱的认证登陆模块,即这里没有登陆,直接利用smtp服务器地址发送出去的。
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart, MIMEBase
from email.header import Header
from email import encoders
from email.utils import parseaddr, formataddr
import smtplib
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
#msg = MIMEText('Hello, send by python3...', 'plain', 'utf-8')
from_addr = input('From: ')
#password = input('Password: ')
to_addr = input('To: ')
smtp_server = input('SMTP server: ')
msg = MIMEMultipart()
#msg = MIMEText('Hello, LittleSisterFairy LJ...', 'plain', 'utf-8')
#msg = MIMEText('<html><body><h1>Hello</h1>' +
#'<p>send by <a href="http://www.python.org">Python</a>...</p>' +
#'</body></html>', 'html', 'utf-8')
msg['From'] = _format_addr('Yihui Zhao <%s>' % from_addr)
#msg['From'] = "Chouzhu"
msg['To'] = _format_addr('You are so smart--<%s>' % to_addr)
msg['Subject'] = Header("From hyz' love...", 'utf-8').encode()
#msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
#msg.attach(MIMEText('LJ, I Love You...', 'html', 'utf-8'))
msg.attach(MIMEText('<html><body><h1>Mosherry_LJ</h1>' + '<p>![](cid:0)</p>' + '</body></html>', 'html', 'utf-8'))
with open("desktop.jpg", 'rb') as f:
mime = MIMEBase('image', 'jpg', filename='lj.jpg')
mime.add_header('Content-Disposition', 'attachment', filename='lj.jpg')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
#server.login(from_addr)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()