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

使用MIMEText()在Python中发送包含附件的邮件

发布时间:2024-01-03 04:07:00

在Python中,可以使用smtplib和email库来发送邮件并附加附件。其中,smtplib提供发送邮件的功能,而email库用于构建邮件的内容。下面是一个使用MIMEText()发送带附件的邮件的例子:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment(sender, receiver, subject, message, attachment_path):
    # 创建一个多部分(multipart)邮件对象
    email = MIMEMultipart()

    # 设置邮件的主题、发件人和收件人
    email['Subject'] = subject
    email['From'] = sender
    email['To'] = receiver

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

    # 读取并附加附件
    with open(attachment_path, 'rb') as attachment:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f"attachment; filename= {attachment_path}")
        email.attach(part)

    # 连接到SMTP服务器并发送邮件
    with smtplib.SMTP('smtp.mailserver.com', 587) as server:
        server.starttls()
        server.login(sender, 'password')
        server.sendmail(sender, receiver, email.as_string())

# 示例用法
sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = '邮件主题'
message = '邮件正文'

# 附件的文件路径
attachment_path = '/path/to/attachment.txt'

send_email_with_attachment(sender, receiver, subject, message, attachment_path)

在以上示例中,我们首先导入了需要的库,然后定义了一个send_email_with_attachment函数,该函数接受发件人、收件人、主题、正文和附件路径作为参数。

函数内部首先创建了一个MIMEMultipart邮件对象,并设置了邮件的主题、发件人和收件人。然后,使用MIMEText创建邮件的正文,并使用email.attach()方法将其添加到多部分邮件对象中。

接下来,打开附件文件,并使用MIMEBase创建一个附件对象。然后,将附件内容设置为文件内容,并使用encoders.encode_base64()方法对其进行编码。最后,使用part.add_header()方法将附件添加到多部分邮件对象中。

最后,使用smtplib.SMTP连接到SMTP服务器,并调用server.login()方法进行登录验证。之后,使用server.sendmail()方法发送邮件,将发件人、收件人和多部分邮件对象转换为字符串形式进行传递。

使用该函数时,只需提供正确的发件人、收件人、主题、正文和附件路径,即可发送带附件的邮件。请注意,需要替换代码中的SMTP服务器地址、端口号、发件人密码以及附件路径和文件名。