最近学习了一下用python发送邮件,现在总结一下,瞬间觉的Python diao bao la。。。
python 发邮件是依赖 STMP模块
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
发送附件邮件:
基本思路就是,使用MIMEMultipart来标示这个邮件是多个部分组成的,然后attach各个部分。如果是附件,则add_header加入附件的声明。
在python中,MIME的这些对象的继承关系如下。
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。
不多说,下面直接上代码:
'''
函数说明:Send_email_text() 函数实现发送带有附件的邮件,可以群发,附件格式包括:xlsx,pdf,txt,jpg,mp3等
参数说明:
1. subject:邮件主题
2. content:邮件正文
3. filepath:附件的地址, 输入格式为["","",...]
4. receive_email:收件人地址, 输入格式为["","",...]
'''
def Send_email_text(subject,content,filepath,receive_email):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
sender = "发送方邮箱"
passwd = "填入发送方密码"
receivers = receive_email #收件人邮箱
msgRoot = MIMEMultipart()
msgRoot['Subject'] = subject
msgRoot['From'] = sender
if len(receivers)>1:
msgRoot['To'] = ','.join(receivers) #群发邮件
else:
msgRoot['To'] = receivers[0]
part = MIMEText(content)
msgRoot.attach(part)
##添加附件部分
for path in filepath:
if ".jpg" in path:
#jpg类型附件
jpg_name = path.split("\\")[-1]
part = MIMEApplication(open(path,'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=jpg_name)
msgRoot.attach(part)
if ".pdf" in path:
#pdf类型附件
pdf_name = path.split("\\")[-1]
part = MIMEApplication(open(path,'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=pdf_name)
msgRoot.attach(part)
if ".xlsx" in path:
#xlsx类型附件
xlsx_name = path.split("\\")[-1]
part = MIMEApplication(open(path,'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=xlsx_name)
msgRoot.attach(part)
if ".txt" in path:
#txt类型附件
txt_name = path.split("\\")[-1]
part = MIMEApplication(open(path,'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=txt_name)
msgRoot.attach(part)
if ".mp3" in path:
#mp3类型附件
mp3_name = path.split("\\")[-1]
part = MIMEApplication(open(path,'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=mp3_name)
msgRoot.attach(part)
try:
s = smtplib.SMTP()
s.connect("smtp.mail.aliyun.com") #这里我使用的是阿里云邮箱,也可以使用163邮箱:smtp.163.com
s.login(sender, passwd)
s.sendmail(sender, receivers, msgRoot.as_string())
print ("邮件发送成功")
except smtplib.SMTPException as e:
print("Error, 发送失败")
finally:
s.quit()
subject = "一波文件测试"
content = "Python 邮件测试"
jpg_path = "a\\b\\1.jpg"
pdf_path = "c.pdf"
txt_path = "d\\e\\f.txt"
file_path = [jpg_path,pdf_path,txt_path] #发送三个文件到两个邮箱
receive_email = ["[email protected]","[email protected]"]
Send_email_text(subject,content,file_path,receive_email)