import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(sender_email, sender_password, recipient_email, subject, body):
# 设置 SMTP 服务器的地址和端口号
smtp_server = 'smtp.126.com'
smtp_port = 465 # SSL连接一般使用465端口
# 创建一个 SSL 连接
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
# 登录到你的邮箱账号
server.login(sender_email, sender_password)
# 创建一个邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
try:
# 发送邮件
server.send_message(msg)
print("邮件发送成功!")
except Exception as e:
print("邮件发送失败:", str(e))
finally:
# 关闭连接
server.quit()
# 使用时调用该函数
send_email('xxxxxxxxxxxx@126.com', '', 'xxxxxxxxxx@qq.com', 'Test Subject', 'Hello, this is a test email!')
-
sender_email: 发件人的电子邮件地址。这是你想要通过该函数发送邮件的邮箱地址。
-
sender_password: 发件人邮箱的密码。为了通过邮件服务器进行身份验证,需要提供发件人邮箱的密码。
-
recipient_email: 收件人的电子邮件地址。这是你想要发送邮件的目标邮箱地址。
-
subject: 邮件的主题。这是邮件的标题,用来简要描述邮件的内容。
-
body: 邮件的正文内容。这是你想要在邮件中传达的消息,可以是文本、HTML或者其他格式。