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

使用Python的email.mime.multipartMIMEMultipart()模块发送复杂邮件

发布时间:2023-12-26 08:28:20

发送复杂邮件可以使用Python的email.mime.multipart模块中的MIMEMultipart类。MIMEMultipart类是MIME消息的一个子类,用于构建带有多个部分的邮件。

下面是一个使用例子,展示如何使用MIMEMultipart类来构建并发送复杂邮件:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

# 邮件发送和接收的相关信息
sender_email = "sender@example.com"
receiver_email = "receiver@example.com"
subject = "复杂邮件测试"

# 创建一个Multipart对象
msg = MIMEMultipart()
msg["Subject"] = subject
msg["From"] = sender_email
msg["To"] = receiver_email

# 添加纯文本内容
text = """\
这是一封复杂邮件示例。
此电子邮件包含文本、图片和附件。
"""
text_part = MIMEText(text, "plain")
msg.attach(text_part)

# 添加图片附件
image_path = "image.jpg"
with open(image_path, "rb") as image_file:
    image_data = image_file.read()
image_part = MIMEImage(image_data, name="image.jpg")
msg.attach(image_part)

# 添加PDF附件
pdf_path = "document.pdf"
with open(pdf_path, "rb") as pdf_file:
    pdf_data = pdf_file.read()
pdf_part = MIMEApplication(pdf_data, name="document.pdf")
msg.attach(pdf_part)

# 发送邮件
try:
    smtp_server = "smtp.example.com"
    smtp_port = 587
    smtp_username = "username"
    smtp_password = "password"
    
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(smtp_username, smtp_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())
    print("邮件发送成功!")
except Exception as e:
    print("邮件发送失败:"+str(e))

在以上例子中,我们首先导入了smtplib、email.mime.multipart、email.mime.text和email.mime.image。然后,我们定义了发送方的email地址、接收方的email地址和邮件的主题。

接下来,我们创建了一个MIMEMultipart对象,并设置了邮件的主题、发件人和收件人。然后,我们使用MIMEText类创建了一个纯文本部分,并使用MIMEMultipart的attach()方法将其附加到邮件中。

接着,我们使用MIMEImage和MIMEApplication类创建了图片和PDF附件,并将它们附加到邮件中。

最后,我们使用smtplib库中的SMTP类来发送邮件。我们首先建立一个与SMTP服务器的连接,调用starttls()方法以启用TLS加密,然后使用login()方法登录SMTP服务器。最后,我们使用sendmail()方法将邮件发送给收件人。

如果成功发送邮件,将打印出"邮件发送成功!";如果发送邮件失败,则会打印出失败的原因。

使用MIMEMultipart类发送复杂邮件允许我们附加多个部分,包括文本、图片和附件。使用这个模块,我们可以轻松构建并发送复杂的邮件。