Python基于smtplib模块发送邮件代码实例
smtplib模块负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。
email模块负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。
email模块下有mime包,mime英文全称为“MultipurposeInternetMailExtensions”,即多用途互联网邮件扩展,是目前互联网电子邮件普遍遵循的邮件技术规范。
该mime包下常用的有三个模块:text,image,multpart。
importsmtplib
fromemail.mime.textimportMIMEText
fromemail.mime.multipartimportMIMEMultipart
fromemail.headerimportHeader
#邮件服务器信息
smtp_server="smtp.qq.com"
port=465#Forstarttls
sender_email="12345689@qq.com"
password=""#getpasswordfrommailsetting
#发送邮件信息,可以发送给多个收件人
receivers=["12345689@163.com","12345689@qq.com"]
subject="ThisisimportPythonSMTP邮件(文件传输)多媒体测试"
#message=MIMEText(text,"plain","utf-8")#文本邮件
message=MIMEMultipart()
message["Subject"]=Header(subject,"utf-8")
message["from"]=sender_email
message["to"]=",".join(receivers)
#邮件正文内容
text="""
DearSir:
howareyou?\n
fordetailinformationplsrefertoattach1。\n
Thefilesyouneedareasfollowed.\n
Ifyouhaveanyconcernplsletmeknown.\n
enjoyyourweekend.\n
BESTREGARDS\n
"""
#message.attach(MIMEText('fordetailinformationplsrefertoattach1。\nThefilesyouneedareasfollowed.\nIfyouhaveanyconcernplsletmeknown.\nenjoyyourweekend','plain','utf-8')
message.attach(MIMEText(text,'plain','utf-8'))
#构造附件1
attach_file1='IMG1965.JPG'
attach1=MIMEText(open(attach_file1,'rb').read(),'base64','utf-8')
attach1["Content-Type"]='application/octet-stream'
attach1["Content-Disposition"]='attachment;filename={0}'.format(attach_file1)
message.attach(attach1)
#构造附件2
attach_file2='YLJ.jpg'
attach2=MIMEText(open(attach_file2,'rb').read(),'base64','utf-8')
attach2["Content-Type"]='application/octet-stream'
attach2["Content-Disposition"]='attachment;filename={0}'.format(attach_file2)
message.attach(attach2)
#Trytologintoserverandsendemail
#server=smtplib.SMTP_SSL(smtp_server,port)
server=smtplib.SMTP_SSL(smtp_server,port)
try:
server.login(sender_email,password)
server.sendmail(sender_email,receivers,message.as_string())
print("邮件发送成功!!!")
print("Mailwith{0}&{1}hasbeensendto{2}successfully.".format(attach_file1,attach_file2,receivers))
exceptExceptionase:
#Printanyerrormessagestostdout
print("Error:无法发送邮件")
print(e)
finally:
server.quit()
结果
邮件发送成功!!!
MailwithIMG1965.JPG&IMG1963.jpghasbeensendto['12345689@163.com','12345689@qq.com']successfully.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。