python已知邮箱和密码,如何自动发送邮件

在 Python 中,可以使用内置的 smtplib 库来发送邮件。已知邮箱和密码时,以下是实现自动发送邮件的完整步骤:


代码实现

示例代码:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(sender_email, sender_password, recipient_email, subject, body):
    try:
        # SMTP服务器配置 (以Gmail为例,可替换为其他服务)
        smtp_server = "smtp.gmail.com"
        smtp_port = 587  # 使用 TLS 的端口

        # 创建邮件对象
        message = MIMEMultipart()
        message["From"] = sender_email
        message["To"] = recipient_email
        message["Subject"] = subject

        # 添加邮件正文
        message.attach(MIMEText(body, "plain"))  # 纯文本邮件正文

        # 连接到SMTP服务器并登录
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()  # 启用 TLS 加密
            server.login(sender_email, sender_password)  # 登录邮箱
            server.sendmail(sender_email, recipient_email, message.as_string())  # 发送邮件
            print("Email sent successfully!")

    except Exception as e:
        print(f"Failed to send email: {
     
     e}")

# 示例调用
if __name__ == "__main__":
    sender_email = "your_email@example.com"
    sender_password = "your_password"
    recipient_email = "recipient@example.com"
    subject = "Test Email"
    body = "This is a test email sent from Python."

    send_email(sender_email, sender_password, recipient_email, subject, body)

配置说明

1. 替换邮箱服务配置
  • Gmail 配置
    • SMTP 服务器:smtp.gmail.com
    • 端口:587(TLS)或 465(SSL)
  • Outlook 配置
    • SMTP 服务器:smtp.office365.com
    • 端口:587
  • QQ 邮箱
    • SMTP 服务器:smtp.qq.com
    • 端口:465(SSL)

根据你的邮箱服务提供商,替换 smtp_serversmtp_port

2. 邮箱设置
  • Gmail
    • 确保启用了“允许不太安全的应用”或使用应用专用密码。
  • QQ 邮箱
    • 需要开启 SMTP 服务,并获取授权码(授权码代替密码)。
  • Outlook
    • 默认支持 SMTP,只需邮箱密码。

重要注意事项

  1. 安全性

    • 不要将明文密码保存在代码中。
    • 使用环境变量或配置文件存储敏感信息。

    示例:使用环境变量

    import os
    sender_password = os.getenv("EMAIL_PASSWORD"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值