title: How to attach a txt file using the current email library?
body: <p>Many of the answers related to this question correspond to an old documentation from the email library (<a href="https://docs.python.org/3.4/library/email-examples.html" rel="nofollow noreferrer">EMAIL OLD DOC.</a>). I want to send an email attaching a txt file with the current documentation (<a href="https://docs.python.org/3/library/email.examples.html" rel="nofollow noreferrer">EMAIL DOC.</a>).</p>
  <p><strong>EXAMPLE:</strong></p>
  <pre class="lang-py prettyprint-override"><code>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)
  </code></pre>