web-dev-qa-db-fra.com

Comment envoyer un e-mail avec une pièce jointe .csv en utilisant Python

D'accord, je sais qu'il y a quelques questions à ce sujet, mais je ne peux pas trouver un moyen de le faire fonctionner correctement. Je suppose que c'est aussi simple que le code ci-dessous, mais cela ne joint pas mon fichier. Toute aide serait grandement appréciée. Je suis également très nouveau sur Python. Existe-t-il un module de messagerie que je devrais importer pour que la fonction fonctionne?

import smtplib
fromaddr = "[email protected]
toaddrs = "[email protected]

msg = "help I cannot send an attachment to save my life"
attach = ("csvonDesktp.csv")

username = user
password = password

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg, attach)
server.quit()
16
Jordan Starrk

Envoyez un e-mail en plusieurs parties avec les types MIME appropriés.

https://docs.python.org/2/library/email-examples.html

Donc quelque chose de possible comme ça (je l'ai testé):

import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

emailfrom = "[email protected]"
emailto = "[email protected]"
fileToSend = "hi.csv"
username = "user"
password = "password"

msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "help I cannot send an attachment to save my life"
msg.preamble = "help I cannot send an attachment to save my life"

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
Elif maintype == "image":
    fp = open(fileToSend, "rb")
    attachment = MIMEImage(fp.read(), _subtype=subtype)
    fp.close()
Elif maintype == "audio":
    fp = open(fileToSend, "rb")
    attachment = MIMEAudio(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
60
Jamie Ivanov

Il y a un exemple complet dans la Python . Je peux copier et coller les parties pertinentes ici mais la page entière n'est pas très longue donc c'est mieux si vous allez et jetez-y un œil.

5
s16h