Jun-26-2024, 12:41 PM
Hi
I'm using python 3.8 and Ubuntu 20.04 as shown below :
I havn't been able to attach files to emails. I tried both the MIMEText module or the email.message module.
With the MIMEText module, I've been able to send the message, however withoutt any file attached to it.
With the email.message module, I followed two examples I found here https://docs.python.org/3.8/library/emai...t=examples in the python documentation.
The first exampli reads
If you want to check on your own system, you can run the following script with two procedure 'envoi_mmt' and 'envoi_emsg'. 'envoi_mmt' sends a email with MIMEText, without attachmemt. 'envoi_emsg' fails with the error "'str' object has no attribute 'header_max_count'".
Arbiel
I'm using python 3.8 and Ubuntu 20.04 as shown below :
arbiel@arbiel-NK3S-8-S4:~$ python Python 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
arbiel@arbiel-NK3S-8-S4:~$ uname -a Linux arbiel-NK3S-8-S4 5.15.0-50-generic #56~20.04.1-Ubuntu SMP Tue Sep 27 15:51:29 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux arbiel@arbiel-NK3S-8-S4:~$.
I havn't been able to attach files to emails. I tried both the MIMEText module or the email.message module.
With the MIMEText module, I've been able to send the message, however withoutt any file attached to it.
With the email.message module, I followed two examples I found here https://docs.python.org/3.8/library/emai...t=examples in the python documentation.
The first exampli reads
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.message import EmailMessage # Open the plain text file whose name is in textfile for reading. with open(textfile) as fp: # Create a text/plain message msg = EmailMessage() msg.set_content(fp.read()) # me == the sender's email address # you == the recipient's email address msg['Subject'] = f'The contents of {textfile}' msg['From'] = me msg['To'] = you # Send the message via our own SMTP server. s = smtplib.SMTP('localhost') s.send_message(msg) s.quit()When executing the instruction as "msg['From'] = me" I got this error message "
arbiel@arbiel-NK3S-8-S4:~$ 'test_courriel.py' envoi_emsg Traceback (most recent call last): File "test_courriel.py", line 160, in <module> envoi_emsg() File "test_courriel.py", line 148, in envoi_emsg msg = entête_msg (msg) File "test_courriel.py", line 99, in entête_msg msg['From'] = tst.exp File "/usr/lib/python3.8/email/message.py", line 399, in __setitem__ max_count = self.policy.header_max_count(name) AttributeError: 'str' object has no attribute 'header_max_count'The second example reads :
Import the email modules we'll need from email.parser import BytesParser, Parser from email.policy import default # If the e-mail headers are in a file, uncomment these two lines: # with open(messagefile, 'rb') as fp: # headers = BytesParser(policy=default).parse(fp) # Or for parsing headers in a string (this is an uncommon operation), use: headers = Parser(policy=default).parsestr( 'From: Foo Bar <[email protected]>\n' 'To: <[email protected]>\n' 'Subject: Test message\n' '\n' 'Body would go here\n') # Now the header items can be accessed as a dictionary: print('To: {}'.format(headers['to'])) print('From: {}'.format(headers['from'])) print('Subject: {}'.format(headers['subject'])) # You can also access the parts of the addresses: print('Recipient username: {}'.format(headers['to'].addresses[0].username)) print('Sender name: {}'.format(headers['from'].addresses[0].display_name))I got the same error message when I tried to attach the pdf file.
If you want to check on your own system, you can run the following script with two procedure 'envoi_mmt' and 'envoi_emsg'. 'envoi_mmt' sends a email with MIMEText, without attachmemt. 'envoi_emsg' fails with the error "'str' object has no attribute 'header_max_count'".
#!/usr/bin/env python import os import sys import os.path import smtplib from email.mime.text import MIMEText from email.message import EmailMessage from email.parser import BytesParser, Parser from email.policy import default ############################################### # définition des identifiants et mots de passe ############################################### def expl_tst (exp="[email protected]", dest="[email protected]", url_serveur='142.250.75.229', mdp='0000' ) : source = '\n'.join(('#!/usr/bin/env python', "exp='"+exp+"'", "dest='"+dest+"'", "url_serveur='"+url_serveur+"'", "mdp='"+mdp+"'", "")) with open (os.path.join(os.path.dirname(sys.argv[0]) + '/tst.py') , 'w') as fichier : fichier.write(source) print(source) try : import tst except: expl_tst() print('Update the file ' + os.path.join(os.path.dirname(sys.argv[0]) + '/tst.py') + ' before running this script again.') sys.exit(1) ############################################### # "printat()" permet de tracer le programme par le numéro de la ligne d'appel ############################################### def printat(*args, **kwargs): """Print function with additional line number and filename information. Adds a string such as "at line 31 in foo.py" to the printed output, to indicate the position where the printat() function was called. All the calls to print() in a program can be changed to provide additional information by adding print = printat at the top of the program. """ import os, sys level = kwargs.pop('level', 0) frame = sys._getframe(level+1) try: lineno, code = frame.f_lineno, frame.f_code args += (f'at line {lineno} in {os.path.basename(code.co_filename)}',) finally: del frame print(*args, **kwargs) ############################################### # Création de la pièce à joindre au message et du corps du message ############################################### def corps_courriel () : printat() return """Bonjour Monsieur, Je vous prie de trouver ci-joint le projet de compte rendu de l'assemblée générale des actionnaires de votre société. Je vous confirme mon accord pour vous rencontrer dans vos locaux le 4 juillet prochain pour en discuter et recueillir vos remarques. En vous souhaitant bonne réception de ce rapport, Sincères salutations. Jean Quidam """ from xhtml2pdf import pisa def enregistre_pdf (): printat() output_filename = '/tmp/test_courriel.pdf' result_file = open(output_filename, "w+b") # convert HTML to PDF pisa_status = pisa.CreatePDF( f_html (), # the HTML to convert dest=result_file) # file handle to recieve result # close output file result_file.close() # close output file # return False on success and True on errors return output_filename def f_html () : printat() return """<!doctype html> <html lang="fr" class="no-js"> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0, width=device-width, viewport-fit=cover"> </head><body> <p> À Montpellier, ville historiquement acquise à la gauche et réputée comme gay-friendly, le phénomène est nouveau. Ces dernières années, un groupe de gros bras néonazis multiplie les attaques. Leur visibilité et la violence de leurs actions, assumée sur les réseaux sociaux la plupart du temps, sont allées crescendo depuis 2022. </p></body></html> """ ############################################### # Envoi du message avec MIMEText ############################################### def envoi_mmt() : printat() texte_message = corps_courriel () msg = MIMEText (texte_message) msg['From'] = tst.exp msg['To'] = tst.dest msg['Subject'] = "Projet de compte rendu de l'assemblée générale" msg['Attachment'] = enregistre_pdf() mailServer = smtplib.SMTP(tst.url_serveur, 1025) ehlo = mailServer.ehlo() print(ehlo) # 4. Of course, we use a secure connection mailServer.starttls() mailServer.ehlo() s = mailServer.login(tst.exp, tst.mdp) printat() print(s) print(msg) # mailServer.sendmail(expediteur, destinataire, msg.as_string()) print(mailServer.send_message(msg, from_addr='<[email protected]>')) mailServer.close() def envoi_emsg () : msg = EmailMessage(corps_courriel ()) exp = 'From: '+ tst.exp.join(('<','>')) dest = 'To: '+ tst.dest.join(('<','>')) objet = "Subject: Projet de compte rendu de l'assemblée générale" headers = Parser(policy=default).parsestr('\n'.join((exp, dest, objet,'',corps_courriel (),''))) fichier=enregistre_pdf() with open(fichier, 'rb') as fp: msg.add_attachment(fp.read(),maintype='application',subtype='pdf', filename=fichier) mailServer = smtplib.SMTP(tst.url_serveur, 1025) ehlo = mailServer.ehlo() mailServer.starttls() mailServer.ehlo() s = mailServer.login(tst.exp, tst.mdp) # print(msg) print(s) print(tst.exp.join(('<','>'))) # mailServer.send_message(msg, from_addr=tst.exp.join(('<','>'))) print(mailServer.send_message(msg, from_addr='<[email protected]>')) mailServer.close() printat() if __name__ == '__main__': code = sys.argv[1] if code == 'envoi_mmt' : envoi_mmt() if code == 'envoi_emsg' : envoi_emsg() if code == 'expl_tst' : expl_tst(exp='[email protected]', dest='[email protected]', url_serveur='127.0.0.1', mdp='7phnuP6EP7npE5w-b6haDg') sys.exit(0)Thank's to anybody who will have the time to provide me with some evidence to get out of this difficulty.
Arbiel
using Ubuntu 18.04.4 LTS, Python 3.8
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)
having substituted «https://www.lilo.org/fr/» to google, «https://protonmail.com/» to any other unsafe mail service and bépo to azerty (french keyboard layouts)