我编写了一个脚本,将图像作为电子邮件的正文发送。但是不是图像,而是随机线。这是我的剧本:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
import smtplib
server = 'smtp.gmail.com'
port = 587
sender = 'mysender@gmail.com'
recipient = 'myreceiver@gmail.com'
subject = 'Gmail SMTP Test'
body = 'blah blah blah'
"Sends an e-mail to the specified recipient."
body = "" + body + "" + msgImage.as_string()
#This is where I have attached the image in body.
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, 'mypassword')
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
这是我收到的邮件:
等等等等blahContent-类型:image / JPEG MIME-版本:1.0内容传输编码:内容的base64-ID:/ 9J / 4AAQSkZJRgABAQEAYABgAAD / 4QBaRXhpZgAATU0AKgAAAAgABQMBAAUAAAABAAAASgMDAAEA AAABAAAAAFEQAAEAAAABAQAAAFERAAQAAAABAAAOw1ESAAQAAAABAAAOwwAAAAAAAYagAACxj // B AEMAAgEBAgEBAgICAgICAgIDBQMDAwMDBgQEAwUHBgcHBwYHBwgJCwkICAoIBwcKDQoKCwwMDAwH CQ4PDQwOCwwMDP / bAEMBAgICAwMDBgMDBgwIBwgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM DAwMDAwMDAwMDAwMDAwMDAwMDAwMDP / AABEIAl0DjQMBIgACEQEDEQH / xAAfAAABBQEBAQEBAQAA AAAAAAAAAQIDBAUGBwgJCgv / xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEU MoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2Rl ZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK 0tPU1dbX2Nna4eLj5OXm5 + jp6vHy8 / T19vf4 + FR / xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUG BwgJCgv /
.......(多行)
非常感谢任何帮助。
就在这里,如果有人能告诉我某种方式以便我可以将图像作为附件发送,那么它对我也会有所帮助。
答案 0 :(得分:0)
您正在创建两条消息:一条带有嵌入图像,另一条带有图像的内部表示,然后发送最后一条消息。这就是为什么你只能得到'胡言乱语'。
为了澄清,您要设置两次电子邮件标题的subject
,from
和to
元素,将正文HTML和图像附加到第一个和{ {1}}到第二个。然后继续发送包含
blah blah blah [图像的字符串表示]
我真的不知道你为什么要做两次这样的工作,但是如果你(如我所说)只想发送一条带有图片的信息,你应该删除第二条信息并仅发送第一条信息({ {1}}代替image.as_string()
)。您发布的代码将是这样的:
msgRoot.as_string()
编辑:如果您删除headers + "\r\n\r\n" + body
,它也可以。但说实话,我不知道是否需要它。