发送一封带附件的邮件

import smtplib
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.application import MIMEApplication



host_server = 'smtp.qq.com' #qq邮箱smtp服务器
sender_qq = '[email protected]'  # sender_sina为发件人的邮箱
pwd = 'xxxxx' # pwd为邮箱的授权码

sender_qq_mail = '[email protected]'  # 发件人的邮箱
receiver = ['[email protected]','[email protected]','[email protected]'] # 收件人的邮箱
 # receiver = [‘[email protected]’,’[email protected]’,’[email protected]’]  # 给多人发送邮件
mail_title = 'python自动化的测试邮件' #邮件的标题
mail_content = ' <html><body><h2>您好,</h2><p>这是一封使用python自动发出的第二份测试邮件</p></body></html> ' #邮件的正文内容
# ‘<html><body><h2>您好</h2>,<p>这是一封使用python登录QQ邮箱发送文本邮件的测试</p></body></html>’

msg = MIMEMultipart()# 邮件的主体
msg['Subject'] = Header(mail_title,'utf-8')
msg['From'] = sender_qq_mail
msg['To'] = Header('测试邮箱','utf-8')
msg.attach(MIMEText(mail_content,'html','utf-8'))  # 邮件正文内容

attachment = MIMEApplication(open(r'C:/Users/13375/Desktop/python/pdf测试.pdf','rb').read()) #打开附件的位置
attachment.add_header('Content-Disposition','attachment',filename='PDFtest.pdf') #附件名称重新命名
msg.attach(attachment)  #将附件添加进邮件

try:
    smtp = SMTP_SSL(host_server)
    smtp.set_debuglevel(1)
    smtp.ehlo(host_server)
    
# smtp = SMTP_SSL(host_server)  # ssl登录
    smtp.login(sender_qq,pwd)
    smtp.sendmail(sender_qq_mail,receiver,msg.as_string())
    smtp.quit()
    print('邮件发送成功')

except smtplib.SMTPException:
    print('无法发送邮件')


猜你喜欢

转载自www.cnblogs.com/tomhu/p/12343105.html