2012-10-25 11 views
9

Eventuali duplicati:
How to send Email Attachments with pythonimmagine allegata per inviare via e-mail utilizzando Python

ho fare un certo lavoro sul sendEmail utilizzando Python ottengo questo codice

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='[email protected]' 
    psw='password' 
    fromaddr= usr 
    toaddr='[email protected]' 
    SendAnEmail(usr, psw, fromaddr, toaddr) 

se ho bisogno di aggiungere un'immagine (allegato un'immagine) come farlo? qualcuno ha idea?

risposta

17
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): 
    img_data = open(ImgFileName, 'rb').read() 
    msg = MIMEMultipart() 
    msg['Subject'] = 'subject' 
    msg['From'] = '[email protected]' 
    msg['To'] = '[email protected]' 

    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() 
3

Leggere i documenti. Le ultime righe dei documenti smtpblib leggere:

Nota In generale, si vuole utilizzare le funzioni del pacchetto e-mail per la costruzione di un messaggio di posta elettronica, che è quindi possibile convertire in una stringa e inviare via sendmail(); vedi email: esempi.

e si punta a: http://docs.python.org/library/email-examples.html#email-examples

che ha un esempio esatto per questo.

+0

uso questi riga per caricare, ma non può funzionare: msg = MimeMultipart() msg.attach (. MIMEImage (file ('linechart.png') read())) –

Problemi correlati