2

这是我用来通过 Python 发送带有附件的电子邮件的代码,但它不适用于 tumblr,基本上,脚本发送的电子邮件正常,但 tumblr 不将其识别为照片帖子,谁能请请让我知道如何解决它?太感谢了,

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

import smtplib
import os

user_name = 'username'
password = 'password'

msg = MIMEMultipart()
msg['Subject'] = 'photo post via email'
msg['From'] = 'from@gmail.com'
msg['To'] = 'to@tumblr.com'

file_path = os.path.join('A_smile_a_day_keeps_the_pain_and_the_doctor_away.jpg')
fp = open(file_path, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(user_name, password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
4

1 回答 1

0

我测试了你的代码,我得到了一个只有文本'photo post via email'但没有图像的帖子。

我测试了下面的代码,我得到了一个带有图像和文本的帖子'photo post via email'

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders

import smtplib
import os

user_name = 'username'
password = 'password'

msg = MIMEMultipart()
msg['Subject'] = 'photo post via email'
msg['From'] = 'from@gmail.com'
msg['To'] = 'to@tumblr.com'

file_path = os.path.join('A_smile_a_day_keeps_the_pain_and_the_doctor_away.jpg')
fp = open(file_path, 'rb')
part = MIMEBase('image', 'jpeg')
part.set_payload( fp.read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_path))
fp.close()
msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(user_name, password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()

关键是使用MIMEBase代替MIMEImage然后对图像进行正确编码并添加正确的标头。

我的代码基于Petri Purho 编写的 auto_tumblr.py

于 2014-02-09T09:17:58.200 回答