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

Python中使用MIMEBase()发送带附件的邮件

发布时间:2024-01-17 01:26:00

在Python中,使用MIMEBase()发送带附件的邮件需要先导入MIMEBase模块和MIMEText模块,并且需要提供正确的邮件服务器的地址、发件人地址、收件人地址、主题、用户名和密码等必要的信息。

下面是一个使用MIMEBase()发送带附件的邮件的例子:

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_attach(sender_email, sender_password, receiver_email, subject, message, attachment):
    # 创建一个MIMEMultipart对象作为邮件的根容器
    msg = MIMEMultipart()

    # 设置邮件的发件人
    msg['From'] = sender_email

    # 设置邮件的收件人
    msg['To'] = receiver_email

    # 设置邮件的主题
    msg['Subject'] = subject

    # 添加文本内容
    msg.attach(MIMEText(message, 'plain'))

    # 添加附件
    attachment_file = open(attachment, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment_file.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment', filename=attachment)
    msg.attach(part)

    # 使用SMTP服务器发送邮件
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login(sender_email, sender_password)
        text = msg.as_string()
        server.sendmail(sender_email, receiver_email, text)
        server.quit()

# 使用示例
sender_email = 'sender@example.com'
sender_password = 'password'
receiver_email = 'receiver@example.com'
subject = '这是一封带附件的邮件'
message = '邮件的正文内容'
attachment = 'path/to/attachment.txt'

send_email_with_attach(sender_email, sender_password, receiver_email, subject, message, attachment)

在上面的示例中,首先导入了需要的模块,然后定义了一个send_email_with_attach()函数,用于发送带附件的邮件。该函数接收发件人邮箱地址、发件人邮箱密码、收件人邮箱地址、主题、邮件正文内容和附件的路径作为参数。

在函数内部,首先创建一个MIMEMultipart对象作为邮件的根容器。然后设置邮件的发件人、收件人和主题。接下来,使用MIMEText模块添加邮件的文本内容。然后,使用MIMEBase模块添加附件,先打开附件文件,然后设置附件的内容和类型,并设置附件的相关信息。最后,使用SMTP服务器发送邮件,先建立一个与SMTP服务器的连接,然后进行登录验证,并发送邮件。

使用时,只需要将发件人邮箱地址、发件人邮箱密码、收件人邮箱地址、主题、邮件正文内容和附件的路径替换为实际的值,并调用send_email_with_attach()函数即可发送带附件的邮件。

注意,需要设置正确的SMTP服务器地址和端口号,并且确保发件人邮箱已开启了SMTP服务。