前言
这里记录一下通过smtp服务使用python发送邮件到163邮箱的小例子。
代码
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
| import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
smtp_server = "smtp.163.com" port = 465 sender_email = "liaozhangsheng@163.com" password = "yourSecretKey" receiver_email = "2087628670@qq.com"
message = MIMEMultipart("alternative") message["Subject"] = "Python SMTP 邮件测试(网易邮箱)" message["From"] = sender_email message["To"] = receiver_email
text = """\ 你好, 这是一封通过Python和网易邮箱发送的测试邮件。\n """
html = """\ <html> <body> <p>你好,<br> 这是一封通过Python和网易邮箱发送的测试邮件。<br> </p> </body> </html> """
part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html")
message.attach(part1) message.attach(part2)
try: with smtplib.SMTP_SSL(smtp_server, port) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) print("邮件发送成功") except Exception as e: print(f"邮件发送失败: {e}")
|