19

Possible Duplicate:
How to send Email Attachments with python

i have do some work on sendEmail using Python i get this code

import smtplib
def SendAnEmail( usr, psw, fromaddr, toaddr):
    # SMTP server
    server=smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(usr,psw)
    # Send 
    msg="text message ....... "

    server.sendmail(fromaddr, toaddr, msg)
    server.quit()
if __name__ == '__main__':
    # Fill info...
    usr='example@sender.ex'
    psw='password'
    fromaddr= usr
    toaddr='example@recevier.ex'
    SendAnEmail( usr, psw, fromaddr, toaddr)

if i need add image (attachment an image) how do that ? anyone have idea ?

Community
  • 1
  • 1

2 Answers2

47
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart


def SendMail(ImgFileName):
    with open(ImgFileName, 'rb') as f:
        img_data = f.read()

    msg = MIMEMultipart()
    msg['Subject'] = 'subject'
    msg['From'] = 'e@mail.cc'
    msg['To'] = 'e@mail.cc'

    text = MIMEText("test")
    msg.attach(text)
    image = MIMEImage(img_data, name=os.path.basename(ImgFileName))
    msg.attach(image)

    s = smtplib.SMTP(Server, Port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(UserName, UserPassword)
    s.sendmail(From, To, msg.as_string())
    s.quit()
Pacil
  • 3
  • 3
user1292828
  • 711
  • 5
  • 5
0

Read the docs. The last few lines of the smtpblib docs read:

Note In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.

and point you to : https://docs.python.org/3/library/email.examples.html

which has an exact example for this.

ProsperousHeart
  • 188
  • 1
  • 14
Jonathan Vanasco
  • 15,111
  • 10
  • 48
  • 72
  • i use these line to load it but cannot work : msg = MIMEMultipart() msg.attach(MIMEImage(file('linechart.png').read())) –  Oct 25 '12 at 14:02
  • As of `2018-05-17` that documentation link is broken. [2.7 Examples](https://docs.python.org/2/library/email-examples.html) and [3.6 Examples](https://docs.python.org/3.6/library/email.examples.html) seem to be current. Please include the code rather than only linking to the code. – CJ Harries May 18 '18 at 16:22