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

使用Python的MIMEApplication()将图片文件作为邮件附件发送

发布时间:2023-12-24 23:41:19

发送带附件的邮件是我们在日常工作和生活中经常遇到的需求。MIMEApplication()是Python的一个模块,用于创建一个MIME类型的消息对象,可以将文件作为附件添加到邮件中。

首先我们需要导入smtplib和MIMEApplication两个模块。smtplib模块用于发送邮件,MIMEApplication模块用于创建附件。

import smtplib
from email.mime.application import MIMEApplication

接下来,我们需要准备一些基本的信息,如发件人、收件人、主题和正文内容。

sender = 'your_email@gmail.com'
password = 'your_password'
receiver = 'recipient_email@gmail.com'
subject = '邮件主题'
message = '邮件正文'

然后,我们需要创建一个Message对象,并设置发件人、收件人、主题和正文。

msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver

接下来,我们需要打开图片文件,并将文件内容作为附件添加到Message对象中。

with open('path_to_image.jpg', 'rb') as f:
    attachment = MIMEApplication(f.read())
    attachment.add_header('Content-Disposition', 'attachment', 
                          filename='image.jpg')
    msg.attach(attachment)

在这个例子中,我们假设图片文件的路径为'path_to_image.jpg',并将附件的文件名设置为'image.jpg'。

最后,我们需要使用SMTP服务器发送邮件。

smtp_server = 'smtp.gmail.com'
smtp_port = 587

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender, password)
    server.send_message(msg)

在这个例子中,我们使用Gmail的SMTP服务器和默认端口587发送邮件。如果使用其他SMTP服务器,需要根据实际情况更改smtp_server和smtp_port。

完整的代码如下:

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

sender = 'your_email@gmail.com'
password = 'your_password'
receiver = 'recipient_email@gmail.com'
subject = '邮件主题'
message = '邮件正文'

# 创建Message对象
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver

# 添加附件
with open('path_to_image.jpg', 'rb') as f:
    attachment = MIMEApplication(f.read())
    attachment.add_header('Content-Disposition', 'attachment', 
                          filename='image.jpg')
    msg.attach(attachment)

# 发送邮件
smtp_server = 'smtp.gmail.com'
smtp_port = 587

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender, password)
    server.send_message(msg)

这就是使用Python的MIMEApplication()将图片文件作为邮件附件发送的例子。你可以根据实际需求修改收件人、发件人、主题、正文和附件的信息,并使用合适的SMTP服务器发送邮件。