Home > Scripts > Sending emails via Gmail with Python3

Sending emails via Gmail with Python3

Worked perfectly in python 3.2 🙂

import smtplib
import os

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

gmail_user = "bond007@gmail.com"
gmail_pwd = "passbond"

def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   encoders.encode_base64(part)
   part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

mail("recepient@gmail.com","Hello from python!","This is a email sent with python","my_attachment.jpg")

Courtesy to KUTUMA
——————–
http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html
——————–

NOTE:
The script in above url works only for python version 2.x .

Advertisements
Categories: Scripts
  1. Ryan
    July 22, 2011 at 1:37 am

    Any info on how to have the “to” address be a group in gmail?

    Also – is it possible to set the font for the message text?

    Thanks.
    – Ryan

  2. Dyego
    September 18, 2011 at 2:35 pm

    Great, thanks a lot !!!

  3. April 5, 2012 at 7:13 pm

    Great script 🙂

    Here is my modification, which adds multiline messages, utf-8 encoding, error checking and comments telling what each part tries to do 🙂

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    #
    # Original copied from here: https://jackal777.wordpress.com/2011/07/19/sending-emails-via-gmail-with-python3/
    # Modifications Mikael Hartzell 2012
    # Feel free to use this code in any way you like 🙂

    import os
    import sys
    import smtplib
    import email
    import email.mime
    import email.mime.text
    import email.mime.multipart

    # You must configure these smpt-server settings before using this script
    use_tsl = False # For Gmail use True
    smpt_server_requires_authentication = False # For Gmail use True
    smtp_username = “firstname.lastname@company.com” # This is the smtp server username and also the sender name of the email.
    smtp_password = “password”
    smtp_server_name = ‘smtp.company.com’ # For Gmail use smtp.gmail.com
    smtp_server_port = 25 # For Gmail use 587

    # Example email message contents
    message_recipient = ‘somebody.somewhere@somecompany.com’
    message_title = ‘Hello from python3 :)’
    message_text_list = [‘This is an email sent with python3, and here are some skandinavian special characters äÄöÖåÅ’, ‘This is the second line of email text’, ‘This is the third line’, ”, ‘Bye :)’]
    message_attachment_path = ” # Set this to the full path of the file you want to attach to the mail or to ” if you do not want to attach anything.

    def send_email(message_recipient, message_title, message_text_string, message_attachment_path):

    # Compile the start of the email message.
    email_message_content = email.mime.multipart.MIMEMultipart()
    email_message_content[‘From’] = smtp_username
    email_message_content[‘To’] = message_recipient
    email_message_content[‘Subject’] = message_title

    # Append the user given lines of text to the email message.
    email_message_content.attach(email.mime.text.MIMEText(message_text_string.encode(‘utf-8′), _charset=’utf-8’))

    # Read attachment file, encode it and append it to the email message.
    if message_attachment_path != ”: # If no attachment path is defined, do nothing.
    email_attachment_content = email.mime.base.MIMEBase(‘application’, ‘octet-stream’)
    email_attachment_content.set_payload(open(message_attachment_path, ‘rb’).read())
    email.encoders.encode_base64(email_attachment_content)
    email_attachment_content.add_header(‘Content-Disposition’,’attachment; filename=”%s”‘ % os.path.basename(message_attachment_path))
    email_message_content.attach(email_attachment_content)

    # Email message is ready, before sending it, it must be compiled into a long string of characters.
    email_message_content_string = email_message_content.as_string()

    # Start communication with the smtp-server.
    try:
    mailServer = smtplib.SMTP(smtp_server_name, smtp_server_port, ‘localhost’, 15) # Timeout is set to 15 seconds.
    mailServer.ehlo()

    # Check if message size is below the max limit the smpt server announced.
    message_size_is_within_limits = True # Set the default that is used if smtp-server does not annouce max message size.
    if ‘size’ in mailServer.esmtp_features:
    server_max_message_size = int(mailServer.esmtp_features[‘size’]) # Get smtp server announced max message size
    message_size = len(email_message_content_string) # Get our message size
    if message_size > server_max_message_size: # Message is too large for the smtp server to accept, abort sending.
    message_size_is_within_limits = False
    print(‘Message_size (‘, message_size, ‘) is larger than the max supported size (‘, server_max_message_size, ‘) of server:’, smtp_server_name, ‘Sending aborted.’)
    sys.exit(1)
    if message_size_is_within_limits == True:
    # Uncomment the following line if you want to see printed out the final message that is sent to the smtp server
    # print(’email_message_content_string =’, email_message_content_string)
    if use_tsl == True:
    mailServer.starttls()
    mailServer.ehlo() # After starting tls, ehlo must be done again.
    if smpt_server_requires_authentication == True:
    mailServer.login(smtp_username, smtp_password)
    mailServer.sendmail(smtp_username, message_recipient, email_message_content_string)
    mailServer.close()

    except smtplib.socket.timeout as reason_for_error:
    print(‘Error, Timeout error:’, reason_for_error)
    sys.exit(1)
    except smtplib.socket.error as reason_for_error:
    print(‘Error, Socket error:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPRecipientsRefused as reason_for_error:
    print(‘Error, All recipients were refused:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPHeloError as reason_for_error:
    print(‘Error, The server didn’t reply properly to the HELO greeting:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPSenderRefused as reason_for_error:
    print(‘Error, The server didn’t accept the sender address:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPDataError as reason_for_error:
    print(‘Error, The server replied with an unexpected error code or The SMTP server refused to accept the message data:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPException as reason_for_error:
    print(‘Error, The server does not support the STARTTLS extension or No suitable authentication method was found:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPAuthenticationError as reason_for_error:
    print(‘Error, The server didn’t accept the username/password combination:’, reason_for_error)
    sys.exit(1)
    except smtplib.SMTPConnectError as reason_for_error:
    print(‘Error, Error occurred during establishment of a connection with the server:’, reason_for_error)
    sys.exit(1)
    except RuntimeError as reason_for_error:
    print(‘Error, SSL/TLS support is not available to your Python interpreter:’, reason_for_error)
    sys.exit(1)

    ####################################
    #### Main Program Starts Here 🙂 ###
    ####################################

    # Consolidate email text lines to one string adding carriage return after each text line.
    message_text_string = ‘\n’.join(message_text_list)

    # Send email
    send_email(message_recipient, message_title, message_text_string, message_attachment_path)

  4. April 5, 2012 at 7:24 pm

    Dang 🙂

    The comment system destroys the formatting of the script rendering it useless 🙂

    Download a copy of the original here: http://dl.dropbox.com/u/2071830/Send_Email_With_Python3.py

    Mikael Hartzell

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: