用python发送邮件需要smtplib,email包,例子如下:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def 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_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 将邮件正文添加到消息中
msg.attach(MIMEText(body, 'plain'))
# 发送邮件
try:
# 连接到 Gmail 的 SMTP 服务器
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls() # 启用 TLS
server.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() # 关闭服务器连接