Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach a txt file in Python smtplib

Tags:

python

email

smtp

I am sending a plain text email as follows:

import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText  def send_message():     msg = MIMEMultipart('alternative')     s = smtplib.SMTP('smtp.sendgrid.net', 587)     s.login(USERNAME, PASSWORD)      toEmail, fromEmail = [email protected], [email protected]     msg['Subject'] = 'subject'     msg['From'] = fromEmail     body = 'This is the message'      content = MIMEText(body, 'plain')     msg.attach(content)     s.sendmail(fromEmail, toEmail, msg.as_string()) 

In addition to this message, I would like to attach a txt file, 'log_file.txt'. How would I attach a txt file here?

like image 679
David542 Avatar asked Mar 02 '12 23:03

David542


People also ask

How do you email a file in Python?

Set up a secure connection using SMTP_SSL() and . starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.

How do I use Smtplib in Python 3?

Python provides smtplib module, which defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon. host − This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com.


2 Answers

The same way, using msg.attach:

from email.mime.text import MIMEText  filename = "text.txt" f = file(filename) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename)            msg.attach(attachment) 
like image 78
Mariusz Jamro Avatar answered Sep 22 '22 01:09

Mariusz Jamro


Since Python3.6, I would recommend start using EmailMessage instead of MimeMultipart. Fewer imports, fewer lines, no need to put the recipients both to the message headers and to the SMTP sender function parameter.

import smtplib from email.message import EmailMessage  msg = EmailMessage() msg["From"] = FROM_EMAIL msg["Subject"] = "Subject" msg["To"] = TO_EMAIL msg.set_content("This is the message body") msg.add_attachment(open(filename, "r").read(), filename="log_file.txt")  s = smtplib.SMTP('smtp.sendgrid.net', 587) s.login(USERNAME, PASSWORD) s.send_message(msg) 

Even better is to install library envelope by pip3 install envelope that's aim is to handle many things in a very intuitive manner:

from envelope import Envelope from pathlib import Path  Envelope()\     .from_(FROM_EMAIL)\     .subject("Subject")\     .to("to")\     .message("message")\     .attach(Path(filename))\     .smtp("smtp.sendgrid.net", 587, USERNAME, PASSWORD)\     .send() 
like image 41
Edvard Rejthar Avatar answered Sep 25 '22 01:09

Edvard Rejthar