本文主要是介绍用python发送邮件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用python发送邮件需要smtplib,email包,例子如下:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipartdef send_email():# 邮件的基本信息sender_email = "x@x.com" # 发送方邮箱receiver_email = "x@x.x.cn" # 接收方邮箱password = "x" # 发送方邮箱密码subject = "blablabalbalbalbal!" # 邮件主题body = "This is a test email sent from Python!" # 邮件正文# 创建一个 MIMEMultipart 对象msg = MIMEMultipart()msg['From'] = sender_emailmsg['To'] = receiver_emailmsg['Subject'] = subject# 将邮件正文添加到消息中msg.attach(MIMEText(body, 'plain'))# 发送邮件try:# 连接到 Gmail 的 SMTP 服务器server = smtplib.SMTP('smtp.office365.com', 587)server.starttls() # 启用 TLSserver.login(sender_email, password) # 登录server.sendmail(sender_email, receiver_email, msg.as_string()) # 发送邮件print("Email sent successfully!")except Exception as e:print(f"Error occurred: {e}")finally:server.quit() # 关闭服务器连接
这篇关于用python发送邮件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!