python使用smtplib发送邮件

xiaohai 2020-10-22 22:48:47 1738人围观 标签: Python 
简介很多业务场景都需要发送邮件,发送邮件也是一个很通用的功能,那么如何在Python中发送电子邮件呢?本文主要记录在python中使用smtplib发送电子邮件。

普通邮件发送 测试使用163邮件成功

#! /usr/bin/env python
# -*- coding: UTF-8 -*-  
import smtplib
from email.mime.text import MIMEText
_user = "发送邮件的邮箱地址"
_pwd  = "发送邮件的邮箱密码"
_to   = "接收邮件的邮箱地址(可以是数组)"

msg = MIMEText("python的测试邮件")
msg["Subject"] = "测试邮件"
msg["From"]    = _user
msg["To"]      = _to

try:
    s = smtplib.SMTP("smtp.163.com", 25)
    s.login(_user, _pwd)
    s.sendmail(_user, _to, msg.as_string())
    s.quit()
    print "Success!"
except smtplib.SMTPException,e:
    print e

以上测试中文字符会出现乱码,为了不出现乱码 需要使用Header进行字符编码转换

#! /usr/bin/env python
# -*- coding: UTF-8 -*-  
import smtplib
from email.mime.text import MIMEText
from email.header import Header
_user = "发送邮件的邮箱地址"
_pwd  = "发送邮件的邮箱密码"
_to   = "接收邮件的邮箱地址(可以是数组)"

message = MIMEText('邮件发送测试...', 'plain', 'utf-8')
message['From'] = _user
message['To'] = _to

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

try:
    s = smtplib.SMTP("smtp.163.com", 25)
    s.login(_user, _pwd)
    s.sendmail(_user, _to, message.as_string())
    s.quit()
    print "Success!"
except smtplib.SMTPException,e:
    print e

对于163邮箱,有反垃圾邮箱机制,所以每次或遇到很多问题,所以使用qq邮箱,以下发送的是html文档

#! /usr/bin/env python
# -*- coding: UTF-8 -*-  
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
_user = "发送邮件的邮箱地址"
_pwd  = "授权码(在qq邮箱下设置,设置过程在后面)"
_to   = "接收邮件的邮箱地址(可以是数组)"


message = MIMEMultipart()
message['From'] = _user
message['To'] = _to

subject = '这是邮件信息好的AA'
message['Subject'] = Header(subject, 'utf-8')

message.attach(MIMEText('<p>这就是信息哟!这是html信息</p><a href="http://www.python.org">Python</a>', 'html', 'utf-8'))
try:
    s = smtplib.SMTP_SSL("smtp.qq.com",465)
    s.login(_user, _pwd)
    s.sendmail(_user, _to, message.as_string())
    s.quit()
    print "Success!"
except smtplib.SMTPException,e:
    print e

QQ邮箱默认没有开启支持POP3/SMTP服务,所以需要在QQ邮箱里面去进行设置,设置后会生成一个授权码,设置过程如下:

  • 1、进入QQ邮箱

  • 2、点击左上角的设置

  • 3、点击账号,进入找到
    image.png

  • 4、开启支持POP3/SMTP服务

  • 5、发送短信

  • 6、生成授权码

生成的授权码是在第三方登陆客户端使用邮箱地址和授权码(等同于密码)进行登录