Search code examples
pythonemailsmtplib

How to attach a txt file using the current email library?


Many of the answers related to this question correspond to an old documentation from the email library (EMAIL OLD DOC.). I want to send an email attaching a txt file with the current documentation (EMAIL DOC.).

EXAMPLE:

import smtplib, ssl
from email.message import EmailMessage
from email.utils import formatdate            


def mail_info(user, message):
    msg = EmailMessage()
    msg['From'] = user
    msg['To'] = user
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = 'Subject'
    msg.add_attachment(message, maintype='text', subtype='txt')
    return msg

def send_mail(message, user, password, smtp_mail, port):
    msg = mail_info(user, message)
    context = ssl.create_default_context()
    
    with smtplib.SMTP_SSL(host=smtp_mail, port=port, context=context) as server:
        '''conect to the server'''
        server.login(user=user, password=password)
        server.sendmail(from_addr=user, to_addrs=user, msg=msg.as_string())    

message = 'This is my email'
with open('filename.txt', 'w+') as f:
    f.write(message)
    attachment = f.read().encode('utf-8')
    send_mail(message=attachment, user=user, password=password, 
              smtp_mail=smtp, port=port)

Solution

  • You just have to use MIMEMultipart as your container, and attach everything to it, so try something like this:

    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText
    from email import encoders
    
    msg = MIMEMultipart()
    msg.attach(MIMEText(body, "plain"))
    
    with open(filename, "r") as attach:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attach.read())
        encoders.encode_base64(part)
        part.add_header(
            "Content-Disposition",
            f"attachment; filename= {filename}",
        )
        msg.attach(part)
    
    ...
    
    send_mail(message=msg, user=user, password=password, smpt_mail=smpt, port=port)