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

使用email.mime.imageMIMEImage()在Python中发送带有图片附件的邮件

发布时间:2023-12-19 01:50:27

使用Python发送带有图片附件的邮件可以使用email和smtplib模块。要发送包含图片附件的邮件,我们需要创建MIMEImage对象并将其添加到MIMEMultipart邮件中。下面是一个发送带有图片附件的邮件的示例:

首先,导入所需的模块:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email import encoders

接下来,定义发送邮件函数:

def send_email(from_email, to_email, subject, message, image_path):
    # 创建MIMEMultipart邮件对象
    msg = MIMEMultipart()

    # 设置邮件内容
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # 添加文本消息到邮件
    msg.attach(MIMEText(message, 'plain'))

    # 读取图片文件
    with open(image_path, 'rb') as f:
        # 创建MIMEImage对象并将其添加到邮件
        image = MIMEImage(f.read())
        image.add_header('Content-Disposition', 'attachment', filename="image.jpg")
        msg.attach(image)

    # 创建SMTP对象并连接到SMTP服务器
    smtp_server = smtplib.SMTP('your_smtp_server', 587)
    smtp_server.starttls()
    smtp_server.login('your_username', 'your_password')

    # 发送邮件
    smtp_server.sendmail(from_email, to_email, msg.as_string())

    # 断开连接
    smtp_server.quit()

现在可以调用send_email函数来发送带有图片附件的邮件。下面是一个示例:

if __name__ == '__main__':
    from_email = 'sender@example.com'
    to_email = 'recipient@example.com'
    subject = 'Test Email with Image Attachment'
    message = 'This is a test email with an image attachment.'
    image_path = 'path_to_image.jpg'

    send_email(from_email, to_email, subject, message, image_path)

在上述示例中,我们首先创建一个MIMEMultipart邮件对象,并设置发件人、收件人和主题。然后我们将邮件内容添加为纯文本消息。

接下来,我们使用open()函数读取图片文件,并创建一个MIMEImage对象。我们还使用add_header()方法为附件设置Content-Disposition标头,其中包括filename参数指定附件的名称。

最后,我们将图片附件添加到邮件,使用指定的发件人、收件人、主题和消息调用send_email函数来发送邮件。

请注意,在实际使用中,您需要替换'your_smtp_server''your_username''your_password'为您的SMTP服务器地址、用户名和密码。

这就是发送带有图片附件的电子邮件的基本示例。您可以根据自己的需求进行调整和扩展。