python smtp 发邮件 添加附件

2023-02-15,,,,

# -*- coding:utf-8 -*-
# __author__ = 'justing' import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication SENDER = "xxx"
PASSWD = "xxx"
SMTPSERVER = "xxx" class Mail(object):
"""
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
注意:邮箱必须开启SMTP才可以通过该脚本发邮件 MIMEBase
|-- MIMENonMultipart
|-- MIMEApplication
|-- MIMEAudio
|-- MIMEImage
|-- MIMEMessage
|-- MIMEText
|-- MIMEMultipart
一般来说,不会用到MIMEBase,而是直接使用它的继承类。MIMEMultipart有attach方法,而MIMENonMultipart没有,只能被attach。
MIME有很多种类型,这个略麻烦,如果附件是图片格式,我要用MIMEImage,如果是音频,要用MIMEAudio,如果是word、excel,我都不知道该用哪种MIME类型了,得上google去查。
最懒的方法就是,不管什么类型的附件,都用MIMEApplication,MIMEApplication默认子类型是application/octet-stream。
"""
def __init__(self, receivers, subject, content, content_type=None, attachment=None, sender=SENDER, passwd=PASSWD,
smtp_server=SMTPSERVER):
self.sender = sender
self.passwd = passwd
self.smtp_server = smtp_server
#receivers type list
self.receivers = receivers
self.subject = subject
self.content = content
self.content_type = content_type
#attachement type is list or str
self.attachment = attachment def attach(self, path):
filename = os.path.basename(path)
with open(path, 'rb') as f:
info = f.read()
attach_part = MIMEApplication(info)
attach_part.add_header('Content-Disposition', 'attachment', filename=filename)
self.msg.attach(attach_part) def handle_attachment(self):
# 支持多个附件
if isinstance(self.attachment, list):
for path in self.attachment:
self.attach(path)
if isinstance(self.attachment, str):
self.attach(path) def handle(self): if not self.content_type or self.content_type == "text":
text = MIMEText(self.content, 'plain', 'utf-8') elif self.content_type == "html":
text = MIMEText(self.content, _subtype='html', _charset='utf-8')
else:
raise "type only support utf and text"
self.msg.attach(text)
if self.attachment:
self.handle_attachment() def send(self):
# 如名字所示: Multipart就是多个部分
self.msg = MIMEMultipart()
self.msg['From'] = self.sender
#msg['To']接收的是字符串而不是list,如果有多个邮件地址,用,分隔即可。
self.msg['To'] = ','.join(self.receivers)
self.msg['Subject'] = self.subject
self.handle() try:
server = smtplib.SMTP(self.smtp_server)
#set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
#server.set_debuglevel(1) server.ehlo()
#加密:调用starttls()方法,就创建了安全连接
server.starttls()
server.login(self.sender, self.passwd)
#self.receivers type list
server.sendmail(self.sender, self.receivers, self.msg.as_string())
server.quit()
except Exception, e:
print "fail to send mail:{}".format(e) receivers = ['xxx@lenovo.com', 'xxx@qq.com']
subject = "This is a TEST"
content = "hello kitty"
content_type = "html"
path = r"D:\workspace\script"
attachment = []
# for parent_dir, child_dirs, filenames in os.walk(path):
# print "parent_dir>>", parent_dir
# print "filenames", filenames # for filename in filenames:
# if filename.split(".")[-1] in ["jpg", "xlsx", "mp3", "png"]:
# attachment.append(os.path.join(parent_dir, filename)) mail = Mail(receivers, subject, content, content_type, attachment)
mail.send()

  

python smtp 发邮件 添加附件的相关教程结束。

《python smtp 发邮件 添加附件.doc》

下载本文的Word格式文档,以方便收藏与打印。