原文:https://blog.csdn.net/sunt2018/article/details/86624045
版权声明:本文为博主原创文章,转载请附上博文链接!
class SendEmail(object):
“”"
Python内置对SMTP的支持,支持发送文本,html样式,还可以带附件。
使用python发邮件,需要使用到两个模块,
email 负责 构造邮件
smtplib 负责发送邮件
“”"
@classmethod
def send_first_email(self):
“”"
发送一个纯文本邮件
“”"
# 使用email模块 构造邮件
from email.mime.text import MIMEText
# 第一个参数,邮件正文
# 第二个参数,_subtype=‘plain’, Content-Type:text/plain,这个应该是一种规范吧?
# 第三个参数 utf-8编码保证兼容
msg = MIMEText(“你害怕大雨吗?”,“plain”,“utf-8”)
# 添加信息防止失败,如果收件人 发件人 标题出现乱码情况, from email.header import Header等方法进行转码
msg[‘From’] = “Tsunxxxxxx@163.com” # 收件人看到的发件人信息
msg[‘To’] = “xxxxxxxxxx@qq.com” #
from email.header import Header
msg[‘Subject’] = “人生苦短,这是标题”
# 发送email
import smtplib
# 邮件SMTP服务器,默认25端口
server = smtplib.SMTP("smtp.163.com",25)
server.set_debuglevel(1) # 这句话,可以打印出和SMTP交互的所有信息
# 发送人的邮件和密码
server.login("xxxxxx@163.com", "xxxxxxx")
# 发件人,收件人列表,msg.as_string()把MIMEText对象变成str
server.sendmail("xxxxxxx@163.com", ["xxxxxxx@qq.com"], msg.as_string())
print("发送成功了")
server.quit()
print("退出")
if name == “main”:
SendEmail.send_first_email()
“”"
还可以发送html 带图片的文件,略
还可以文本和html混合发送
msg = MIMEMultipart(‘alternative’)
msg[‘From’] = …
msg[‘To’] = …
msg[‘Subject’] = …
msg.attach(MIMEText(‘hello’, ‘plain’, ‘utf-8’))
msg.attach(MIMEText(‘
Hello
’, ‘html’, ‘utf-8’))正常发送msg对象…
smtp_server = ‘smtp.gmail.com’
smtp_port = 587
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
剩下的代码和前面的一模一样:
server.set_debuglevel(1)
…
发送附件
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
if name == ‘main’:
fromaddr = ‘137xxxx@163.com’
password = ‘password’
toaddrs = [‘137xxxx@163.com’, ‘137xxxx@qq.com’]
content = 'hello, this is email content.'
textApart = MIMEText(content)
imageFile = '1.png'
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
pdfFile = '算法设计与分析基础第3版PDF.pdf'
pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
zipFile = '算法设计与分析基础第3版PDF.zip'
zipApart = MIMEApplication(open(zipFile, 'rb').read())
zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
m = MIMEMultipart()
m.attach(textApart)
m.attach(imageApart)
m.attach(pdfApart)
m.attach(zipApart)
m['Subject'] = 'title'
try:
server = smtplib.SMTP('smtp.163.com')
server.login(fromaddr,password)
server.sendmail(fromaddr, toaddrs, m.as_string())
print('success')
server.quit()
except smtplib.SMTPException as e:
print('error:',e) #打印错误