如何使用 Python 发送带附件的电子邮件

如何使用 Python 发送带附件的电子邮件

在之前的系列文章中,我们已经讨论了如何配置和使用 SMTP 与 IMAP 服务来发送和接收电子邮件,并提供了如何在 Gmail 和 QQ 邮箱中启用这些服务的具体步骤。为了方便读者了解完整的背景信息,这里我们将提供前几篇文章的链接:

在这篇文章中,我们将详细介绍如何使用 Python 的 smtplib 模块以及 email 库来构建和发送带有附件的电子邮件。

示例代码

import os
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from urllib.parse import quote

"""
EMAIL_HOST: SMTP 服务器地址
EMAIL_PORT: SMTP 服务器端口
EMAIL_USER: 登录 SMTP 服务器的账号
EMAIL_AUTH: 登录 SMTP 服务器的授权码
"""

# 邮件服务器配置
smtp_configs = {
    'qq': {
        'host': 'smtp.qq.com',                  # 邮件服务器域名(自行修改)
        'port': 465,                            # 邮件服务端口(通常是465)
        'user': 'user@qq.com',         			# 登录邮件服务器的账号(自行修改)
        'auth': 'your_authcode'              	# 开通SMTP服务的授权码(自行修改)(不是填入QQ的密码)
    },
    'gmail': {
        'host': 'smtp.gmail.com',               # 邮件服务器域名(自行修改)
        'port': 587,                            # 邮件服务端口(通常是587)
        'user': 'user@gmail.com',      			# 登录邮件服务器的账号(自行修改)
        'auth': 'your_authcode'              	# 配置IMAP/SMTP服务的授权码(应用密码)(需要去谷歌配置)
    }
}

# 定义函数来发送电子邮件
def send_email(*, Sender, Recipient, Subject='', Content='', Attachment=[], Service='qq'):
    try:
        print("开始构建邮件...")
        email = MIMEMultipart()
        email['From'] = Sender
        email['To'] = Recipient
        email['Subject'] = Header(Subject, 'utf-8')

        message = MIMEText(Content, 'plain', 'utf-8')
        email.attach(message)

        for filename in Attachment:
            with open(filename, 'rb') as file:
                attachment = MIMEApplication(file.read(), Name=os.path.basename(filename))
                attachment['Content-Disposition'] = f'attachment; filename="{quote(os.path.basename(filename))}"'
                email.attach(attachment)

        print("邮件构建完成,准备发送...")

        config = smtp_configs.get(Service)
        if not config:
            raise ValueError(f"Unsupported email Service provider: {Service}")

        EMAIL_HOST = config['host']
        EMAIL_PORT = config['port']
        EMAIL_USER = config['user']
        EMAIL_AUTH = config['auth']

        if EMAIL_PORT == 465:
            smtp = smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT)
        else:
            smtp = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
            smtp.starttls()  # 启用 TLS 加密

        smtp.login(EMAIL_USER, EMAIL_AUTH)
        smtp.sendmail(Sender, Recipient.split(';'), email.as_string())
        print("邮件发送成功")
    except smtplib.SMTPAuthenticationError:
        print("SMTP Authentication Error: Please check your credentials.")
    except smtplib.SMTPServerDisconnected:
        print("SMTP Server Disconnected: Please check your network connection and server settings.")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        smtp.quit()
        print("SMTP会话已关闭。")
        
"""
发送邮件

:param Sender:      发件人(可包含名称和邮箱地址)
:param Recipient:   收件人,多个收件人用英文分号进行分隔
:param Subject:     邮件的主题
:param Content:     邮件正文内容
:param Attachment:  附件要发送的文件路径列表
"""

# 调用函数发送 Gmail 邮箱邮件
send_email(
    Sender = '发件人<user@gmail.com>',
    Recipient = '收件人<recipient1@gmail.com>;recipient2@qq.com',
    Subject = '邮件的主题',
    Content = '邮件正文内容',
    Attachment = ['附件要发送的文件路径列表'],
    Service='gmail'
)

# 调用函数发送 QQ 邮箱邮件
send_email(
    Sender = 'GLNG<user@qq.com>',
    Recipient = 'Gwyn Winthrop<recipient@qq.com>',
    Subject = 'Invitation to the Annual Conference',
    Content = '''
                Dear Mr. Doe,

                We would like to formally invite you to attend our annual conference on innovation and technology, which will be held on October 20th at the Grand Convention Center. Your expertise in this field would be greatly appreciated by all attendees.

                Please find attached the agenda for the conference and an RSVP form for confirming your attendance.

                We look forward to your participation and hope to see you there.

                Kind regards,

                Jane Smith
    ''',
    Attachment = ['./path/to/attachment1', './path/to/attachment2'],
    Service='qq'
)
注意事项
  • 安全性和隐私:在使用此脚本时,请确保您的登录凭据不会泄露给第三方。最好是在本地环境中测试并运行此类脚本。
  • 错误处理:上述代码包含了基本的错误处理逻辑,但是根据具体需求可能还需要增加更详细的异常捕获和日志记录功能。
  • 服务器配置:根据所使用的邮件服务提供商的不同,SMTP 主机地址、端口号以及其他设置可能会有所不同。请参考相应的服务文档来获取正确的配置信息。

以上就是如何使用 Python 发送带附件的电子邮件的全部内容。如果您有任何疑问或需要进一步的帮助,请随时提问!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咖喱年糕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值