NicoVanDerDussen
Posts: 74
Joined: Sat Aug 24, 2013 2:41 pm

Sending attachements by e-mail

Mon Sep 08, 2014 11:19 am

Hi,

I'm trying to send a JPG by e-mail.

Googling for Python Email Attachment gives quite a few results, but I don't get it to work properly.

Using
http://code4reference.com/2013/07/simpl ... -an-email/

gives a attachment ATT00001 which does not open.

Others also fail to give me the proper solution.

What is the "best" way for a novice to send e-mail by Python?

Thanks
Nico
Setting up your Raspberry Pi to work with a 3G dongle http://nvdd.info/11gKrsZ

User avatar
DougieLawson
Posts: 39885
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Sending attachements by e-mail

Mon Sep 08, 2014 12:22 pm

Code: Select all

import time
from datetime import datetime
import picamera
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

with picamera.PiCamera() as camera:
   camera.resolution = (1024, 768)
   camera.start_preview()
   # Camera warm-up time
   time.sleep(2)
   camera.capture('photo.jpg')

f_time = datetime.now().strftime('%a %d %b @ %H:%M')

toaddr = 'someone@example.com'    # redacted
me = 'picamera@mydomainname.co.uk' # redacted
subject = 'Photo ' + f_time

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = me
msg['To'] = toaddr
msg.preamble = "Photo @ " + f_time

fp = open('photo.jpg', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

try:
   s = smtplib.SMTP('localhost')
   s.send_message(msg)
   s.quit()
except:
   print ("Error: unable to send email")
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

NicoVanDerDussen
Posts: 74
Joined: Sat Aug 24, 2013 2:41 pm

Re: Sending attachements by e-mail

Mon Sep 08, 2014 1:13 pm

Hi,

thanks for the example code - I hacked it to work with GMail and added a few items from others.

I left the redundant coded as comments deliberately.

Code: Select all

#http://www.raspberrypi.org/forums/viewtopic.php?f=32&t=86441

import time
from datetime import datetime
#import picamera
from smtplib import SMTP
from smtplib import SMTPException
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

"""
with picamera.PiCamera() as camera:
   camera.resolution = (1024, 768)
   camera.start_preview()
   # Camera warm-up time
   time.sleep(2)
   camera.capture('photo.jpg')
"""

f_time = datetime.now().strftime('%a %d %b @ %H:%M')

toaddr = 'to@outlook.com'    # redacted
me = 'me@gmail.com' # redacted
subject = 'Photo ' + f_time

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = me
msg['To'] = toaddr
msg.preamble = "Photo @ " + f_time

fp = open('photo.jpg', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

try:
   s = smtplib.SMTP('smtp.gmail.com',587)
   s.ehlo()
   s.starttls()
   s.ehlo()
   s.login(user = 'me@gmail.com',password = 'super_password')
   #s.send_message(msg)
   s.sendmail(me, toaddr, msg.as_string())
   s.quit()
#except:
#   print ("Error: unable to send email")
except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
It still send the attachment without the file name .

ATT00001 instead of photo.jpg.

I appreciate being able to learn from those who walked the way long before me :)
Setting up your Raspberry Pi to work with a 3G dongle http://nvdd.info/11gKrsZ

NicoVanDerDussen
Posts: 74
Joined: Sat Aug 24, 2013 2:41 pm

Re: Sending attachements by e-mail

Mon Sep 08, 2014 2:02 pm

Hi,

seems as if I found a solution :D

Code: Select all

#!/usr/bin/python

# You are entering crocodile infested water!
# A noob at work!
#
# Retrieved from http://solvingmytechworld.blogspot.com/2013/01/send-email-through-gmail-running-script.html
# Kept all the main code, but hacked a bit
#

 
# Import smtplib for the actual sending function
import smtplib
 
# For guessing MIME type
import mimetypes
 
# Import the email modules we'll need
import email
import email.mime.application
 
#Import sys to deal with command line arguments
import sys
 
# Create a text/plain message
msg = email.mime.Multipart.MIMEMultipart()
msg['Subject'] = 'subject_you_prefer'
msg['From'] = 'from@gmail.com'
msg['To'] = 'receivers_mail@gmail.com'

 
# The main body is just another attachment
body = email.mime.Text.MIMEText("""Here you can write as many things as you want!""")
msg.attach(body)
 
# PDF attachment block code
# Nico: Ok, use a fixed image...and a jpg not pdf
 
#directory=sys.argv[1]
directory = 'photo.jpg'
 
# Split de directory into fields separated by / to substract filename
 
spl_dir=directory.split('/')
 
# We attach the name of the file to filename by taking the last
# position of the fragmented string, which is, indeed, the name
# of the file we've selected
 
filename=spl_dir[len(spl_dir)-1]
 
# We'll do the same but this time to extract the file format (pdf, epub, docx...)
 
spl_type=directory.split('.')
 
type=spl_type[len(spl_type)-1]
 
fp=open(directory,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype=type)
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(att)
 
# send via Gmail server
# NOTE: my ISP, Centurylink, seems to be automatically rewriting
# port 25 packets to be port 587 and it is trashing port 587 packets.
# So, I use the default port 25, but I authenticate.
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login('from@gmail.com','super_password')
s.sendmail('from@gmail.com','receiver@outlook.com', msg.as_string())
s.quit()

Setting up your Raspberry Pi to work with a 3G dongle http://nvdd.info/11gKrsZ

Mizzy50
Posts: 1
Joined: Sat Apr 11, 2015 4:38 pm

Re: Sending attachements by e-mail

Sat Apr 11, 2015 4:49 pm

From where do I get these library files
import datetime
import smtplib
import MIMEImage
import MIMEMultipart

User avatar
DougieLawson
Posts: 39885
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Sending attachements by e-mail

Sat Apr 11, 2015 7:26 pm

I think all of those python modules are part of the base install.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Return to “Python”