最近在学习Python,顺便看了下邮件发送,发现代码还是挺简单的。但是注意图片发送,要在邮箱中开启显示额我就是被坑了,以为是我的代码问题折腾许久。
# -*- coding:utf-8 -*- """ 功能: 使用一言API和壁纸API合并为一封邮件,再发送出去 作者: 赤域吧_AQ 联系方式:chiyuba@qq.com 作者主页: https://itzhai.cn """ import smtplib from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header sender = 'chiyuba@88.com' receivers = ['1530687053@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 msgRoot = MIMEMultipart('related') msgRoot['From'] = Header("it宅", 'utf-8') msgRoot['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' msgRoot['Subject'] = Header(subject, 'utf-8') msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) mail_msg = """ <html><body><p>Python 发送的邮件测试</p> <p><a href="http://chiyuba.com">赤域吧</a></p> <p>图片演示:</p> <p><img src="cid:image1"></p></body></html> """ msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8')) # 指定图片为当前目录 fp = open('15851507208080.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # 定义图片 ID,在 HTML 文本中引用 msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) try: email_user = "chiyuba@88.com" email_pwd = "6666" mail_host = "smtp.88.com" mail_port = 465 smtp = smtplib.SMTP_SSL(mail_host) smtp.connect(mail_host, mail_port) smtp.login(email_user, email_pwd) smtp.sendmail(sender, receivers, msgRoot.as_string()) smtp.quit() print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
原文地址: https://itzhai.cn/xuexijiaocheng/1144.html