欢迎访问宙启技术站
智能推送

用Python发送带有附件的电子邮件(使用MIMEText)

发布时间:2023-12-23 09:53:49

发送带有附件的电子邮件通常使用Python标准库中的smtplib和email模块来实现。在使用email模块创建带附件的邮件时,我们需要使用MIMEText类来创建邮件正文,同时使用MIMEBase和MIMEApplication来创建邮件附件。

下面是一个使用Python发送带有附件的电子邮件的示例代码:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_email_with_attachment(sender_email, sender_password, recipient_email, subject, message, attachment_path):
    # 创建MIMEMultipart对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject

    # 创建邮件正文
    msg.attach(MIMEText(message, 'plain'))

    # 读取附件内容并添加到邮件中
    with open(attachment_path, 'rb') as attachment:
        attachment_content = attachment.read()
    attachment_name = attachment_path.split('/')[-1]
    attachment_mime = MIMEApplication(attachment_content)
    attachment_mime.add_header('Content-Disposition', 'attachment', filename=attachment_name)
    msg.attach(attachment_mime)

    # 发送邮件
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login(sender_email, sender_password)
        smtp.send_message(msg)

# 示例使用:
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
recipient_email = 'recipient_email@example.com'
subject = 'Test Email with Attachment'
message = 'This is a test email with attachment.'
attachment_path = '/path/to/attachment.txt'

send_email_with_attachment(sender_email, sender_password, recipient_email, subject, message, attachment_path)

以上代码创建了一个MIMEMultipart对象,将发件人、收件人、主题、邮件正文添加到其中。然后,它读取附件文件的内容,并使用MIMEApplication创建一个附件。最后,它使用smtplib库连接到SMTP服务器,并通过SMTP发送邮件。

请确保将your_email@gmail.com替换为您的发件人电子邮件地址,将your_password替换为您的发件人电子邮件密码,将recipient_email@example.com替换为收件人电子邮件地址,并设置正确的附件路径attachment_path

希望以上示例对您有所帮助!