你真的懂邮件吗?邮件包括如下四部分内容:

  • 发送人:from_addr
  • 接收人:to_addr
  • 主题:subject
  • 正文:msg(mime text 格式文本)

其中发送者,接收者,又需要两部分的内容构成:用户名(字符串形式)及其邮件地址(xx@xx.com)。

from email.mime.text import MIMEText
from email.header import Header
from email.utils import parseaddr, formataddr
import smtplib

def format_addr(s):
    name, addr = parseaddr(s)    # 将 s 解析为用户名,邮件地址,比如 s = '用户1 <%s>' % 'xx@xx.com'
    return formataddr((Header(name, 'utf-8').encode(), addr))

def email_server(server_ip, server_port):
    return smtplib.SMTP(server_ip, server_port)

# MIMEText 正文内容
mimetext = MIMEText('hello there, when u read this, means ...', 'plain', 'utf-8')

from_addr = 'xxx@xxx.com'
password = 'xxxxxx'
from_info = '用户1<%s>' % from_addr

to_addr = 'xxxx@xxxx.com'
to_info = '用户2<%s>' % to_addr

mimetext['From'] = format_addr(from_info)
mimetext['To'] = format_addr(to_info)
mimetext['Subject'] = Header('邮件测试', 'utf-8').encode()

# 网易邮箱服务器
server_ip = 'smtp.126.com'
server = email_server(server_ip, server_port=25)
# 登陆
server.login(from_addr, password)
# 发送邮件
server.sendmail(from_addr, [to_addr], mimetext.as_string())
server.quit()


这里写图片描述

posted on 2018-01-03 22:48  未雨愁眸  阅读(376)  评论(0编辑  收藏  举报