def AttacheFichiersJoints(self, email=None): for fichier in self.fichiers: """Guess the content type based on the file's extension. Encoding will be ignored, altough we should check for simple things like gzip'd or compressed files.""" ctype, encoding = mimetypes.guess_type(fichier) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compresses), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fichier) # Note : we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fichier, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() else: fp = open(fichier, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(part) # Set the filename parameter nomFichier = os.path.basename(fichier) if type(nomFichier) == six.text_type: nomFichier = FonctionsPerso.Supprime_accent(nomFichier) # changement cosmetique pour ajouter les guillements autour du filename part.add_header('Content-Disposition', "attachment; filename=\"%s\"" % nomFichier) email.attach(part)
def Envoi_mail(adresseExpediteur="", listeDestinataires=[], listeDestinatairesCCI=[], sujetMail="", texteMail="", listeFichiersJoints=[], serveur="localhost", port=None, avecAuthentification=False, avecStartTLS=False, listeImages=[], motdepasse=None, accuseReception=False): """ Envoi d'un mail avec pièce jointe """ import smtplib import poplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.MIMEAudio import MIMEAudio from email.Utils import COMMASPACE, formatdate from email import Encoders import mimetypes assert type(listeDestinataires) == list assert type(listeFichiersJoints) == list # Corrige le pb des images embarquées index = 0 for img in listeImages: img = img.replace(u"\\", u"/") img = img.replace(u":", u"%3a") texteMail = texteMail.replace( _(u"file:/%s") % img, u"cid:image%d" % index) index += 1 # Création du message msg = MIMEMultipart() msg['From'] = adresseExpediteur msg['To'] = ";".join(listeDestinataires) msg['Bcc'] = ";".join(listeDestinatairesCCI) msg['Date'] = formatdate(localtime=True) msg['Subject'] = sujetMail if accuseReception == True: msg['Disposition-Notification-To'] = adresseExpediteur msg.attach(MIMEText(texteMail.encode('utf-8'), 'html', 'utf-8')) # Attache des pièces jointes for fichier in listeFichiersJoints: """Guess the content type based on the file's extension. Encoding will be ignored, altough we should check for simple things like gzip'd or compressed files.""" ctype, encoding = mimetypes.guess_type(fichier) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compresses), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fichier) # Note : we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fichier, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(fichier, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fichier, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(part) # Set the filename parameter nomFichier = os.path.basename(fichier) if type(nomFichier) == unicode: nomFichier = FonctionsPerso.Supprime_accent(nomFichier) part.add_header('Content-Disposition', 'attachment', filename=nomFichier) msg.attach(part) # Images incluses index = 0 for img in listeImages: fp = open(img, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image%d>' % index) msgImage.add_header('Content-Disposition', 'inline', filename=img) msg.attach(msgImage) index += 1 ## pop = poplib.POP3(serveur) ## print pop.getwelcome() ## pop.user(adresseExpediteur) ## pop.pass_(motdepasse) ## print pop.stat() ## print pop.list() ## Certains SMTP (exemple Orange Pro) demandent une authentifcation (en général user : boite mail et pwd : mot de passe associé au smtp sécurisé ) ## mais ne supportent pas le mode starttls ## Ces identifiants sont généralement utilisés lors d'un envoi de mail abec un FAI différent du propriétaire du SMTP ## Par exemple pour envoyer un mail avec le smtp pro orange depuis un autre FAI (Free, SFR....) ## serveur : smtp.premium.orange.fr - port 587 ## user : [email protected] ## pwd : mon_pwd ## On positionne dans ce cas le parametre avecAuthentification a True ## et le parametre avecStartTLS est positionné selon l'état du support de la fonction startTLS par le SMTP if motdepasse == None: motdepasse = "" if avecAuthentification in (0, False, None): # Envoi standard smtp = smtplib.SMTP(serveur, timeout=150) else: # Si identification SSL nécessaire : smtp = smtplib.SMTP(serveur, port, timeout=150) smtp.ehlo() if avecStartTLS == True: smtp.starttls() smtp.ehlo() smtp.login(adresseExpediteur.encode('utf-8'), motdepasse.encode('utf-8')) smtp.sendmail(adresseExpediteur, listeDestinataires + listeDestinatairesCCI, msg.as_string()) smtp.close() return True
def EnvoyerEmail(self, commentaires="", listeFichiers=[]): """ Envoi d'un mail avec pièce jointe """ import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.MIMEAudio import MIMEAudio from email.Utils import COMMASPACE, formatdate from email import Encoders import mimetypes IDrapport = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # texte if len(commentaires) == 0: commentaires = _(u"Aucun") texteMail = _( u"<u>Envoi de %d fichier(s) de traduction pour Noethys :</u><br/><br/>%s<br/><br/><u>Commentaires :</u><br/><br/>%s" ) % (len(listeFichiers), ", ".join(listeFichiers), commentaires) # Destinataire listeDestinataires = [ "noethys" + "@gmail.com", ] # Expéditeur dictExp = self.GetAdresseExpDefaut() if dictExp == None: dlg = wx.MessageDialog( self, _(u"Vous devez d'abord saisir une adresse d'expéditeur depuis le menu Paramétrage > Adresses d'expédition d'Emails." ), _(u"Erreur"), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() return False adresseExpediteur = dictExp["adresse"] serveur = dictExp["smtp"] port = dictExp["port"] ssl = dictExp["ssl"] motdepasse = dictExp["motdepasse"] utilisateur = dictExp["utilisateur"] # Création du message msg = MIMEMultipart() msg['From'] = adresseExpediteur msg['To'] = ";".join(listeDestinataires) msg['Date'] = formatdate(localtime=True) msg['Subject'] = _(u"Envoi de fichiers de traduction Noethys") msg.attach(MIMEText(texteMail.encode('utf-8'), 'html', 'utf-8')) # Attache des pièces jointes for fichier in listeFichiers: """Guess the content type based on the file's extension. Encoding will be ignored, altough we should check for simple things like gzip'd or compressed files.""" ctype, encoding = mimetypes.guess_type(fichier) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compresses), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fichier) # Note : we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fichier, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(fichier, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fichier, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(part) # Set the filename parameter nomFichier = os.path.basename(fichier) if type(nomFichier) == unicode: nomFichier = FonctionsPerso.Supprime_accent(nomFichier) part.add_header('Content-Disposition', 'attachment', filename=nomFichier) msg.attach(part) if ssl == False: # Envoi standard smtp = smtplib.SMTP(serveur) else: # Si identification SSL nécessaire : smtp = smtplib.SMTP(serveur, port, timeout=150) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(utilisateur.encode('utf-8'), motdepasse.encode('utf-8')) try: smtp.sendmail(adresseExpediteur, listeDestinataires, msg.as_string()) smtp.close() except Exception, err: dlg = wx.MessageDialog( self, _(u"Le message n'a pas pu être envoyé.\n\nErreur : %s !") % err, _(u"Envoi impossible"), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() return False