title: Sending an e-mail through Python
body: <p>I've tried the code below to send a csv file to an e-mail address but for some reason the console shows the script running and it doesn't seem to end/execute. The script works fine without the csv attachment so I'm wondering if it has something to do with the code pertaining to the attachment.</p>
  <p>Can someone please help? :(</p>
  <pre><code>import email, smtplib, ssl
  
  from email import encoders
  from email.mime.base import MIMEBase
  from email.mime.multipart import MIMEMultipart
  from email.mime.text import MIMEText
  
  port = 465  # For SSL
  subject = &quot;&quot;
  body = &quot;&quot;
  sender_email = &quot;&quot;
  receiver_email = &quot;&quot;
  password = &quot;&quot;
  
  # Create a multipart message and set headers
  message = MIMEMultipart()
  message[&quot;From&quot;] = sender_email
  message[&quot;Subject&quot;] = subject
  message[&quot;Bcc&quot;] = receiver_email  # Recommended for mass emails
  
  # Add body to email
  message.attach(MIMEText(body, &quot;plain&quot;))
  
  filename = &quot;EarningsReleaseData.csv&quot;  # In same directory as script
  
  # Open file in binary mode
  with open(filename, &quot;rb&quot;) as attachment:
      # Add file as application/octet-stream
      # Email client can usually download this automatically as attachment
      part = MIMEBase(&quot;application&quot;, &quot;octet-stream&quot;)
      part.set_payload(attachment.read())
  
  # Encode file in ASCII characters to send by email    
  encoders.encode_base64(part)
  
  # Add header as key/value pair to attachment part
  part.add_header('Content-Disposition', 'attachment', filename = filename)
  
  # Add attachment to message and convert message to string
  message.attach(part)
  text = message.as_string()
  
  # Log in to server using secure context and send email
  context = ssl.create_default_context()
  with smtplib.SMTP_SSL(&quot;smtp.gmail.com&quot;, port, context=context) as server:
      server.login(sender_email, password)
      server.sendmail(sender_email, receiver_email, message)
  </code></pre>