import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 发送方邮箱和授权码(或密码)
sender_email = "your_email@example.com"
password = "your_password_or_app_specific_password"
# 接收方邮箱
receiver_email = "recipient@example.com"
# 创建邮件对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Python Email Test"
# 邮件正文
body = "This is a test email sent from Python."
message.attach(MIMEText(body, "plain"))
# 连接到SMTP服务器并发送邮件
try:
server = smtplib.SMTP("smtp.example.com", 587) # 使用适当的SMTP服务器和端口
server.starttls() # 启用TLS加密
server.login(sender_email, password)
text = message.as_string()
server.sendmail(sender_email, receiver_email, text)
print("Email sent successfully!")
except Exception as e:
print(f"Error: {e}")
finally:
server.quit()
smtplib 来发送邮件,并使用 email.mime.text.MIMEText 和 email.mime.multipart.MIMEMultipart 来构建邮件内容。MIMEMultipart() 创建一个可以包含多个部分的邮件对象,设置发件人、收件人和主题。MIMEText 添加邮件正文,并将其附加到邮件对象中。smtplib.SMTP() 连接到SMTP服务器,启用TLS加密,登录发件人邮箱,发送邮件,最后关闭连接。请根据实际情况修改 smtp.example.com 和端口号,以及发件人和收件人的邮箱地址。
上一篇:python中type的用法
下一篇:python中的换行符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站