如何通过Python脚本发布tumblr照片帖子

时间:2013-09-23 00:19:24

标签: python tumblr

这是我用来通过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()

1 个答案:

答案 0 :(得分: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然后对图像进行正确编码并添加正确的标题。

我的代码基于auto_tumblr.py written by Petri Purho