在电子邮件Python中嵌入图像

时间:2014-08-10 17:08:57

标签: python email sendmail html-email spam

下面给出了使用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 ID发送电子邮件。它工作正常。但是在这里,只要我尝试在电子邮件中嵌入图像,接收方电子邮件服务器就会将此电子邮件视为垃圾邮件,如上面的代码所示。如果我没有尝试嵌入图片,则会按预期在目的地收到html和纯文本电子邮件。 我还尝试使用静态http网址嵌入图像作为图像src。但那时问题也存在。但是,当我尝试使用一些 https 图片网址时,接收方正确收到的电子邮件。

接收方电子邮件过滤由 postini 提供支持。

可能是什么问题?有什么办法可以修改上面的代码来摆脱这个问题。

感谢。

1 个答案:

答案 0 :(得分:0)

你可以看看这个答案: Python: Mail sent by script is marked as spam by Gmail

另一个选择 - 避免被标记为垃圾邮件 - 是使用某些服务,如AWS SES。