我正在尝试使用python中的smtplib发送带有图像的电子邮件。电子邮件在我的桌面和iphone gmail应用程序上显示正常,但在标准的iphone邮件应用程序上,主体不显示。这是我的代码:
def send_html_email(self, subject, html, to_email,from_email, password, from_name, image=None):
msg = MIMEMultipart('alternative')
msg['From'] = from_name
msg['To'] = to_email
msg['Subject'] = subject
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msg.as_string().encode('utf-8'))
session.quit()
似乎当我不添加图像时,电子邮件会随身体发送。关于如何使用图像的任何想法?
答案 0 :(得分:0)
这似乎有效:
def send_html_email(self, subject, html, to_email, from_email, password, from_name, image=None):
msgRoot = MIMEMultipart('related')
msgRoot['From'] = from_name
msgRoot['To'] = to_email
msgRoot['Subject'] = subject
msg = MIMEMultipart('alternative')
msgRoot.attach(msg)
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msgRoot.as_string().encode('utf-8'))
session.quit()