# _*_ coding: utf-8 _*_"""python发送邮件"""import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipart# 第三方 SMTP 服务(以腾讯企业邮件和QQ邮箱为例)mail_host = "smtp.exmail.qq.com"# mail_host = "smtp.qq.com"mail_user = "from@from.com.cn"# mail_user = "from@qq.com"mail_pass = "授权码"mail_sender = mail_usermail_port = 465mail_receivers = ["to@to.com", "to@qq.com"]# 设置邮件格式、内容等 -- 普通格式 ================================================message = MIMEText("邮件内容", "plain", "utf-8")# 设置邮件格式、内容等 -- HTML格式 ===============================================msg_html = """<p>Python 邮件发送测试...</p><p><a href="http://www.runoob.com">这是一个链接</a></p><table border="1"><tr><th>Month</th><th>Savings</th></tr><tr><td>January</td><td>100ドル</td></tr><tr><td>February</td><td>80ドル</td></tr></table>"""message = MIMEText(msg_html, "html", "utf-8")# 设置邮件格式、内容等 -- HTML格式(带有图片和附件)==================================msg_html = """<p>Python 邮件发送测试...</p><p><a href="http://www.runoob.com">这是一个链接</a></p><p>图片演示:</p><p><img src="cid:image_id_1"></p>"""msg_content = MIMEText(msg_html, "html", "utf-8")msg_image = MIMEImage(open("test.png", "rb").read())msg_image.add_header("Content-ID", "<image_id_1>")msg_file = MIMEText(open("test.csv", "rb").read(), "base64", "utf-8")msg_file["Content-Type"] = "application/octet-stream"msg_file["Content-Disposition"] = "attachment; filename=\"test.csv\""message = MIMEMultipart("related")message.attach(msg_content)message.attach(msg_image)message.attach(msg_file)# ==============================================================================# 设置邮件的收发件、标题等message["From"] = mail_sendermessage["To"] = ";".join(mail_receivers)message["Subject"] = Header("邮件标题", "utf-8")try:# 登录,并发送邮件smtpObj = smtplib.SMTP_SSL(mail_host, mail_port)smtpObj.login(mail_user, mail_pass)smtpObj.sendmail(mail_sender, mail_receivers, message.as_string())print("success")except smtplib.SMTPException as excep:print("error", excep)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。