1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import smtplib from smtplib import SMTP_SSL from email.mime.image import MIMEImage 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' sender_sina_mail = '878891611@qq.com' receiver = ['878891611@qq.com'] pwd = 'unjwwrsj'
mail_title = 'python自动化办公' mail_content = """ <p>Python 邮件发送测试...</p> <p><a href="http://www.runoob.com">这是一个链接</a></p> <p>图片演示:</p> <p><img decoding="async" src="cid:image1"></p> """
msg = MIMEMultipart() msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_sina_mail msg["To"] = Header("测试邮箱", 'utf-8') msg.attach(MIMEText(mail_content, 'html', 'utf-8')) ''' 附件部分 Content-Disposition() 内容设置 设置的内容attachmen 附件 filename给它重命名 ''' attachment = MIMEApplication(open('./py测试目录/客户1_价格通知.docx', 'rb').read()) attachment.add_header('Content-Disposition', 'attachment', filename='客户1-价格通知.docx') msg.attach(attachment) ''' 发送正文带图片的邮件 '''
fp = open('安静.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close()
msgImage.add_header('Content-ID', '<image1>') msg.attach(msgImage)
try: smtp = SMTP_SSL(host_server, 465) smtp.set_debuglevel(0) smtp.login(sender_sina_mail, pwd) smtp.sendmail(sender_sina_mail, receiver, msg.as_string()) smtp.quit() print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
|