美文网首页
Python || 发送邮件

Python || 发送邮件

作者: 有个水友 | 来源:发表于2017-02-12 20:13 被阅读834次

使用Python的stmplibemail发送邮件:

一、纯文本邮件

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

#=========================================
#格式化email的头部信息,不然会出错,当做垃圾邮件
#=========================================
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = "your email"
password = "密码或者授权码"
to_addr = "target email"
smtp_server = "smtp.163.com"

#======================================
#注意添加Subject、To和From三个字段
#======================================
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['From'] = _format_addr('Tracy的Python <%s>' % from_addr)
msg['To'] = _format_addr('You <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP……', 'utf-8').encode()

server = smtplib.SMTP(smtp_server, 25)
#打印与服务器的交互信息
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

二、HTML邮件

只需要在构造MIMEText时,传入HTML字符串,并且将第二个参数设置为html即可。

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

#=========================================
#格式化email的头部信息,不然会出错,当做垃圾邮件
#=========================================
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = "your email"
password = "密码或者授权码"
to_addr = "target email"
smtp_server = "smtp.163.com"

#==========================================================
#注意添加Subject、To和From三个字段,更换字符串,改变第二个参数即可
#==========================================================
msg = MIMEText("<html><body><h1>Hello</h1>"+ 
"<p>send by <a href='http://www.baidu.com/'>Python</a>" + 
"</body></html>", 'html', 'utf-8')
msg['From'] = _format_addr('Tracy的Python <%s>' % from_addr)
msg['To'] = _format_addr('You <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP……', 'utf-8').encode()

server = smtplib.SMTP(smtp_server, 25)
#打印与服务器的交互信息
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

三、发送带附件的邮件

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

#=========================================
#格式化email的头部信息,不然会出错,当做垃圾邮件
#=========================================
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = "your email"
password = "密码或者授权码"
to_addr = "target email"
smtp_server = "smtp.163.com"

#======================================================
#带附件的邮件可以看做包含若干部分的邮件:文本和各个附件本身,
#所以,可以构造一个MIMEMultipart对象代表邮件本身,
#然后往里面加上一个MIMEText作为邮件正文,
#再继续往里面加上表示附件的MIMEBase对象即可。
#=====================================================
# 邮件对象:
msg = MIMEMultipart()
msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
msg['To'] = _format_addr('管理员 <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

# 邮件正文是MIMEText:
msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))

# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('/Users/michael/Downloads/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)

server = smtplib.SMTP(smtp_server, 25)
#打印与服务器的交互信息
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

4、搬运

#=========================================================================
# 加密SMTP
#
# 使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。
#要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,
#然后再使用SMTP协议发送邮件。网易163的STMP服务SSL端口号为465/994  
#=========================================================================

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

import smtplib

# return Alias_name <xxxx@example.com>


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

# 接收参数: 发件人地址
from_addr = ''

# 接收参数: 客户端授权密码
passwd = ''

# 接收参数: 收件人地址,可多个
to_addrs = ["abc@qq.com"]

# 接收参数: SMTP服务器(注意:是发件人的smtp服务器)
smtp_server = 'smtp.163.com'


# 接收参数: 邮件主题
subject = '人生苦短'

# 接收参数: 邮件正文
plain = '我用python!'

# 带附件邮件
# 指定subtype为alternative,同时支持html和plain格式
msg = MIMEMultipart('alternative')
# 邮件正文中显示图片,同时附件的图片将不再显示
# plain = 'Hello world and hello me!'
msg.attach(MIMEText(str(plain), 'plain', 'utf-8'))       # 纯文本
# html = '<html><body><h1>Hello</h1><p>![](cid:0)</p></body></html>'
# msg.attach(MIMEText(html, 'html', 'utf-8'))         # HTML
# 添加附件:即关联一个MIMEBase,图片为本地读取
with open('/home/kyxy/Desktop/dota.png', 'rb') as f:
    # 设置附件中的MIME和文件名
    mime = MIMEBase('image', 'jpeg', filename='dota.png')
    # 加上必要的头信息
    mime.add_header('Content-Disposition', 'attachment',
                    filename='dota.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)

# 未指定用户别名,则客户端会自动提取邮件地址中的名称作为邮件的用户别名
msg['From'] = _format_addr(from_addr)
# msg['To'] = _format_addr(to_addrs)
msg['To'] = '%s' % ','.join([_format_addr('<%s>' % to_addr)
                             for to_addr in to_addrs])
msg['Subject'] = Header(str(subject), 'utf-8').encode()
msg['Date'] = formatdate()


#=========================================================================
# 发送邮件
#=========================================================================
try:
    # SMTP服务器设置(地址,端口):
    server = smtplib.SMTP_SSL(smtp_server, 465)
    # server.set_debuglevel(1)
    # 连接SMTP服务器(发件人地址, 客户端授权密码)
    server.login(from_addr, passwd)

    # 发送邮件
    server.sendmail(from_addr, to_addrs, msg.as_string())

    print('邮件发送成功')

except smtplib.SMTPException as e:
    print(e)
    print('邮件发送失败')

finally:
    # 退出SMTP服务器
    server.quit()

相关文章

网友评论

      本文标题:Python || 发送邮件

      本文链接:https://www.haomeiwen.com/subject/hnwaittx.html