Here's the code that I'm using to send email with attachments via Python, but it does not work well with tumblr, basically, the email sent by the script went through okay, but tumblr does not recognize it as photo post, could anyone please kindly let me know how to fix it? Thank you so much,
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()
I tested your code and I got a post with just the text 'photo post via email'
but with no image.
I tested the following code and I got a post with the image and the text '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()
The key point is to use MIMEBase
instead of MIMEImage
and then to properly encode the image and add a proper header.
My code is based on auto_tumblr.py written by Petri Purho.