我有一个Python脚本,用于发送包含不同数量的内嵌图像的电子邮件,并且它实际上按预期工作,但有一个例外。每个图像也作为附件发送,使每个图像出现两次。即使在禁用脚本的许多部分后,我也无法找到导致重复的原因。
!/usr/bin/python
coding: utf-8
import os, sys
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.mime.base import MIMEBase
from email import encoders import smtplib
try:
strTo = ‘’’Joe@Email.com’’’
strFrom = ‘’’Jim@Some.biz’’’
msg = MIMEMultipart()
msg['Subject'] = ‘’’Photo Test’’’
msg['From'] = '''Jim@Some.biz'''
msg['Reply-to'] = '''Jim@Some.biz'''
msg['To'] = ‘’’Joe@Email.com’’’
msg.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 email agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgText = MIMEText(''' words here, then the image followed by more words here''', 'plain')
msgAlternative.attach(msgText)
msgText = MIMEText('''<p>words here, then the image</p><p><img src="cid:image1"></p><p>followed by more words here</p><p></p>''','html')
msgAlternative.attach(msgText)
# Attach Any Images
if '''/Users/jim/Desktop/003.jpg''' != "":
images = '''/Users/jim/Desktop/003.jpg'''.splitlines()
i=1
for image in images:
# print 'Image',i,': ',image,'\n'
fp = open(image, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image'+str(i)+'>')
msg.attach(msgImage)
i+=1
#send the email
smtp = smtplib.SMTP_SSL(‘’’mailserver.net''', '''465''')
smtp.ehlo()
smtp.login('''Jim@Some.biz''', ‘’’xxxxxx’’’)
smtp.sendmail(strFrom,strTo.split(","), msg.as_string())
smtp.quit() except: print("Sending Error : "+strTo)
如何阻止图像附件?
答案 0 :(得分:0)
简单的解决方案,一旦找到:
msg = MIMEMultipart()
应该是
msg = MIMEMultipart('related')