python发邮件代码怎么写

45次阅读
没有评论

共计 950 个字符,预计需要花费 3 分钟才能阅读完成。

要在 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 服务器的文档。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-16发表,共计950字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)