ITPub博客

首页 > 应用开发 > Python > 使用 Python 发送带有附件的电子邮件。

使用 Python 发送带有附件的电子邮件。

原创 Python 作者:mingtian66 时间:2024-11-25 11:22:49 0 删除 编辑

使用 Python 发送带有附件的电子邮件,你可以使用 email 和 smtplib 这两个内置库。下面是一个完整的示例,展示了如何发送带有附件的电子邮件:

  1. ‌ 设置电子邮件的账号和配置‌(例如 SMTP 服务器地址、端口、账号和密码)。
  2. ‌ 创建电子邮件消息‌(包括收件人、发件人、主题、正文和附件)。
  3. ‌ 通过 SMTP 服务器发送电子邮件‌。

以下是示例代码:

pythonCopy Codeimport smtplibfrom email.message import EmailMessagefrom email.utils import formataddrfrom email.mime.application import MIMEApplication# 电子邮件账号配置smtp_server = 'smtp.example.com'  # 例如:smtp.gmail.comsmtp_port = 587  # 或 465(SSL)sender_email = 'your_email@example.com'sender_name = 'Your Name'sender_password = 'your_password'recipient_email = 'recipient@example.com'# 创建电子邮件消息msg = EmailMessage()
msg['From'] = formataddr((sender_name, sender_email))
msg['To'] = recipient_email
msg['Subject'] = 'Subject of the Email'msg.set_content('This is the body of the email.')# 添加附件file_path = 'path/to/your/file.txt'with open(file_path, 'rb') as file:
    mime_app = MIMEApplication(file.read(), Name='file.txt')
msg.attach(mime_app)# 发送电子邮件try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()  # 如果使用 SSL,请注释此行并使用 server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    server.login(sender_email, sender_password)
    server.send_message(msg)    print('Email sent successfully with attachment.')except Exception as e:    print(f'Failed to send email: {e}')finally:
    server.quit()

注意事项:

  1. ‌ SMTP 服务器‌:确保 smtp_server 和 smtp_port 配置正确。常见的 SMTP 服务器地址例如 Gmail 是 smtp.gmail.com,端口 587 用于 STARTTLS,端口 465 用于 SSL。

  2. ‌ 账号安全‌:

    • 确保发件人邮箱账号和密码正确。
    • 对于 Gmail,你需要启用 "低安全性应用访问",或者使用应用专用密码。
    • 建议使用环境变量或安全存储凭据,而不是直接在代码中硬编码。
  3. ‌ 附件路径‌:确保 file_path 指向你想要附加的文件。

  4. ‌ 错误处理‌:生产代码中应包含更详细的错误处理,以处理例如网络问题、认证失败等情况。

这个示例应该能帮助你发送带有附件的电子邮件。如果你使用其他邮件服务提供商,请相应地调整 SMTP 服务器地址和端口。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3051085/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2024-08-07

  • 博文量
    589
  • 访问量
    602952