温馨提示×

python发邮件代码怎么写

小亿
90
2023-11-07 20:17:52
栏目: 编程语言

要在Python中发送邮件,你可以使用内置的smtplib库。以下是一个简单的示例代码,可以通过SMTP服务器发送电子邮件:

import smtplib
from email.mime.text import MIMEText

def send_email(subject, message, from_email, to_email, smtp_server, smtp_port, smtp_username, smtp_password):
    # 创建邮件内容
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    # 连接SMTP服务器并发送邮件
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.login(smtp_username, smtp_password)
    server.sendmail(from_email, [to_email], msg.as_string())
    server.quit()

# 使用示例
subject = "Hello"
message = "This is a test email."
from_email = "from@example.com"
to_email = "to@example.com"
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_username = "username"
smtp_password = "password"

send_email(subject, message, from_email, to_email, smtp_server, smtp_port, smtp_username, smtp_password)

在上面的示例中,你需要将示例数据替换为实际的SMTP服务器和电子邮件帐户信息。此外,还需要安装Python模块emailsmtplib,可以使用pip命令进行安装。

请注意,有些SMTP服务器可能需要启用SMTP身份验证或使用SSL / TLS加密。要进行这些设置,请查阅你所使用的SMTP服务器的文档。

0