在Python中将图片嵌入邮件中

7 投票
1 回答
3811 浏览
提问于 2025-04-18 16:45

下面是用Python发送嵌入图片的邮件的代码。

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

# Define these once; use them twice!
strFrom = 'from@sender.com'
strTo = 'to@example.com'

# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)

# This example assumes the image is in the current directory
fp = open('test.jpg', 'rb')

msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

# Send the email (this example assumes SMTP authentication is required)
import smtplib
smtp = smtplib.SMTP()
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()

我遇到的问题非常具体,跟接收方的邮箱服务器有关。我用同样的代码给一个GMail邮箱发送邮件,结果很好。但是在这里,接收方的邮箱服务器把我发送的邮件当成垃圾邮件,每次我尝试在邮件中嵌入图片时,都会出现这个问题。如果我不嵌入图片,那么无论是HTML格式还是纯文本格式的邮件,都会正常送达。

我也尝试过用静态的HTTP网址作为图片的来源,但问题依然存在。不过,当我使用一些HTTPS的图片网址时,邮件就能正常送达接收方。

接收方的邮件过滤是由postini提供支持的。

这可能是什么问题呢?有没有什么方法可以修改上面的代码,解决这个问题?

谢谢。

1 个回答

0

你可以看看这个回答:Python:通过脚本发送的邮件被Gmail标记为垃圾邮件

还有一个选择——为了避免被标记为垃圾邮件,可以使用一些服务,比如AWS SES。

撰写回答