Embedding image in email Python

2020-07-11 05:16发布

Code used for sending an image embedded email using python is given below.

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()

My problem is very specific to the receiver email server. I used the same code to send an email to a GMail id. It worked fine. But here, the receiver email server is considering this email as spam whenever I tries to embed an image in the email as shown in the above code. If I am not trying to embed the image, then both html and plain text emails are getting received at the destination as expected. I tried also embedding images with static http urls as the image src. But then also the problem exists. But when i tried using some https image urls, the emails where properly received at the receiver side.

The receiver side email filtering is powered by postini.

What might be the problem? Is there any way by which I can modify the above code to get rid of this problem.

Thanks.

1条回答
小情绪 Triste *
2楼-- · 2020-07-11 05:55

You might take a look at this answer: Python: Mail sent by script is marked as spam by Gmail

Another option - to avoid been marked as SPAM - is to use some service like AWS SES.

查看更多
登录 后发表回答