Attaching an Image to Python Email

The code used to send inline email using python is 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 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 recipient's email server. I used the same code to send an email to GMail ID. It worked fine. But here, the recipient's mail server treats this email as spam when I try to embed an image in an email, as shown in the code above. If I am not trying to embed an image , then both html and text messages are received at the destination, as expected. I also tried embedding images with static http addresses as an src image. But then the problem exists. But when I tried to use some https urls, emails that were correctly received on the recipient side.

Recipient-side email filtering is powered by postini .

What could be the problem? Is there a way in which I can modify the above code to get rid of this problem.

Thanks.

+6
source share
1 answer

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

Another option - in order not to be marked as SPAM - use some service, such as AWS SES.

0
source

Source: https://habr.com/ru/post/973611/


All Articles