Browsing Tag


Cool Stuff, Programming Languages, Python

Sending Email From Python Using Command Line

January 10, 2014

Since many of my commenters ask for something a little more advance in Python, I wrote up this script I wrote. Notice that this script will allow you to use almost anything you would come to except from an email client. Sending Email From Python is simpler than you think. That includes cc and bcc fields, html mode and attachment files. You will have to use your own email configuration, I left the settings from gmail, but any email account could be used. Just fill in your user name and password. You can include this module and use the compose_email() function to send emails directly from you Python program. As a word of advice, try to not send too many emails all at once (like 400 emails). Gmail will not send the emails and your email address will be marked as spam. Use with caution.

NOTE: The only output of the program is a single print statement (assuming it all went well), that will indicate an email has been sent.

#account setup
username = '***';
password = '***';
server = '';

from time import sleep;
import smtplib;
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText;
from email.mime.multipart import MIMEMultipart;

# create msg - MIME* object
# takes addresses to, from cc and a subject
# returns the MIME* object
def create_msg(to_address,

    msg = MIMEMultipart();
    msg['Subject'] = subject;
    msg['To'] = to_address;
    msg['Cc'] = cc_address;
    msg['From'] = from_address;
    return msg;

# send an email
# takes an smtp address, user name, password and MIME* object
# if mode = 0 sends to and cc
# if mode = 1 sends to bcc
def send_email(smtp_address, usr, password, msg, mode):
    server = smtplib.SMTP(smtp_address);
    if (mode == 0 and msg['To'] != ''):
        server.sendmail(msg['From'],(msg['To']+msg['Cc']).split(","), msg.as_string());
    elif (mode == 1 and msg['Bcc'] != ''):
    elif (mode != 0 and mode != 1):
        print 'error in send mail bcc'; print 'email cancled'; exit();

# compose email
# takes all the details for an email and sends it
# address format: list, [0] - to
#                       [1] - cc
#                       [2] - bcc
# subject format: string
# body format: list of pairs [0] - text
#                            [1] - type:
#                                        0 - plain
#                                        1 - html
# files is list of strings
def compose_email(addresses, subject, body, files):

    # addresses
    to_address = addresses[0];
    cc_address = addresses[1];
    bcc_address = addresses[2];

    # create a message
    msg = create_msg(to_address, cc_address=cc_address , subject=subject);

    # add text
    for text in body:
        attach_text(msg, text[0], text[1]);

    # add files
    if (files != ''):
        file_list = files.split(',');
        for afile in file_list:
            attach_file(msg, afile);

    # send message
    send_email(server, username, password, msg, 0);

    # check for bcc
    if (bcc_address != ''):
        msg['Bcc'] = bcc_address;
        send_email(server, username, password, msg, 1);

    print 'email sent'

# attach text
# attaches a plain text or html text to a message
def attach_text(msg, atext, mode):
    part = MIMEText(atext, get_mode(mode));

# util function to get mode type
def get_mode(mode):
    if (mode == 0):
        mode = 'plain';
    elif (mode == 1):
        mode = 'html';
        print 'error in text kind'; print 'email cancled'; exit();
    return mode;

# attach file
# takes the message and a file name and attaches the file to the message
def attach_file(msg, afile):
    part = MIMEApplication(open(afile, "rb").read());
    part.add_header('Content-Disposition', 'attachment', filename=afile);

#to be tested...
              'test v.5.0',
              [['some text goes here...\n',0]],

#compose_email can take the following arguments:
#	1. to recipients (separated by a comma)
#	2. cc recipients (separated by a comma)
#	3. bcc recipients (separated by a comma)
#	4. subject
#	5. a list with message and mode (plain txt or html)
#	6. files to be attached


Why Switching to RackSpace Mail is Worth the $2

May 23, 2013

Some of my clients live in the dark age of fighting off email storage limits. To me this is a thing of the past. We are in the year of 2013, I can buy a 1 TB hard drive for $60 off of Amazon, having a 1GB email limit sounds absurd to me. Yet, there are many provides that take advantage of consumers who do not know any better. Begin a well informed consumer is always a benefit. I strongly advise anyone to do their own research and not relay on my words and/or opinions. Just for a quick compression, Google Gmail will give you 10+ GB for free. However, using Gmail is not always a good solution when you are a legitimate business and must maintain a professional approach. Seriously, put yourself in the shoes of your clients. If you were communicating with a sales person and got a proposal from the following 2 addresses, which are you more likely to not consider junk? or

It is obvious that the ladder is a better selection. You most likely already have a website for your company, if not, you should. So you have the domain name and regular email from your own hosting provide. For example, HostGator will say that you have unlimited storage. In reality, at 1 GB emails sent to your mailbox will bounce back to the sender. You could delete old email, but what if you want to keep some for archiving, marketing or even legal future usage? The answer is that you need more storage. In part, that is one of the reason I suggest to my customers to move to RackSpace for their email provider. You can still keep your domain name and hosting at different locations and just have your email service through RackSpace Email.


RackSpace offers 2 different packages, they offer regular email mailboxes for $2 per month per mailbox and for $10 they offer full exchange. This leads me to some “hidden benefits” RackSpace has. Quite often people like to use Microsoft Exchange as a way to scare people into buying equipment that can sum up to $10K and more. The truth is that if all you need is the following times, most likely RackSpace email will do the trick for you.

  • 25GB Mailbox
  • Contacts
  • Calendar
  • Tasks
  • Notes

The system will allow you to share contacts and calendar appointments as well as keep personal ones. In a nut shell, it will give you all the power of exchange without you having to worry or pay an arm and a leg. Now, Microsoft Exchange does have some more advance features. If you really need it, you could go with that option, for $10 you can have it all. If you want you can even take the system out for a RackSpace Email Test Drive. Here are some screen shoots of their system taken directly oof of RackSpace website:






I hope I at least got you thinking about your email service. Yes, you can get away with free email, but you usually get what you pay for. For my client RackSpace might work. For others it may not. We live in a “Zero Time Communication Age”. Internal and external digital communication has to be fast and reliable in order to succeeded. I feel confidante that the migration for my client will work well and that I will be able to share their experiences in the near future. If I have not convinced you yet, I suggest you start a chat with one of the RackSpace support or sale staff. They are always their to answer question and are very knowledgeable.