Python构建带图片的MIMEText邮件
发布时间:2023-12-11 13:47:14
Python提供了多种库可以实现邮件的发送和处理,其中最常用的是smtplib和email库。smtplib库用于连接和发送邮件,email库用于构建邮件内容。
首先,我们需要导入smtplib和email库:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage
接下来,我们需要设置发件人、收件人和邮件主题:
fromaddr = "example@gmail.com" password = "examplepassword" toaddr = "receiver@example.com" subject = "Hello, this is a test email"
然后,我们可以创建一个MIMEMultipart对象,用于存储邮件的多种格式(如纯文本、HTML和图片):
msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = subject
接下来,我们可以将纯文本或HTML内容添加到邮件中:
1. 添加纯文本内容:
body = "This is the body of the email" msg.attach(MIMEText(body, 'plain'))
2. 添加HTML内容:
html = """ <html> <body> <h1>This is the HTML body of the email</h1> <p>Here is an image:</p> <img src="cid:image1"> </body> </html> """ msg.attach(MIMEText(html, 'html'))
接下来,我们可以将图片添加到邮件中:
with open("image.jpg", "rb") as fp:
img = MIMEImage(fp.read())
img.add_header('Content-ID', '<image1>')
msg.attach(img)
在将图片添加到邮件中时,需要设置Content-ID标头并在HTML内容中引用该标头,以便在邮件中显示图片。上述代码将图片命名为image.jpg,并将其添加到邮件中。
最后,我们可以使用smtplib库连接到SMTP服务器并发送邮件:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
上述代码使用Gmail作为SMTP服务器,并通过TLS进行安全连接。你需要将邮箱地址和密码替换为真实的发件人邮箱和密码。
下面是一个完整的例子,演示了如何使用Python构建带图片的MIMEText邮件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
fromaddr = "example@gmail.com"
password = "examplepassword"
toaddr = "receiver@example.com"
subject = "Hello, this is a test email"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject
body = "This is the body of the email"
msg.attach(MIMEText(body, 'plain'))
html = """
<html>
<body>
<h1>This is the HTML body of the email</h1>
<p>Here is an image:</p>
<img src="cid:image1">
</body>
</html>
"""
msg.attach(MIMEText(html, 'html'))
with open("image.jpg", "rb") as fp:
img = MIMEImage(fp.read())
img.add_header('Content-ID', '<image1>')
msg.attach(img)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
这样,我们就可以使用Python构建带图片的MIMEText邮件并发送出去了。如果收件人支持HTML格式的邮件,他们将能够在收件箱中看到图像的显示。
