Python Sending Email

Facebooktwitterredditpinterestlinkedinmailby feather

Python Sending Email

Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software running in our computer, our computer packages the message and sends it using SMTP.

There are many open, free-to-use SMTP servers, but these are frequently used by spammers and blocked by most incoming mail servers. It is better to use a password-protected SMTP server because your mail will likely reach the recipient instead of getting filtered and dumped into the recipient’s spam folder.

A typical email requires the following parameters:

  • Recipient email address
  • Sender email address
  • Message Subject
  • Message Body
  • Attachments (if any, not required)
  • SMTP server address
  • SMTP port (usually 25, but could also be 2525 or 587 as alternatives)

Python provides smtplib module, which describes an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener deamon. The syntax is following:

  • host:  Host runs in SMTP server. You can specify the IP address of the host or a domain name like The host is an optional argument.
  • port_no: It is necessary to provide the port number if we are giving host argument.
  • local_hostname: If the SMTP server is running on your local machine, then you can specify just localhost for this option.

An SMTP object has an instance method called sendmail, which is typically used to do work of mailing a message. It accepts three parameters-

  • The sender – A string with the address of the sender.
  • The receiver – A list of strings, one for each recipient.
  • The message A message as a string formatted as stated in the various RFCs.

Sending email using SMTP

Sending email using Gmail

In the few cases where emails are sent using Gmail SMTP server. In this case, we can pass gmail as the SMTP server instead of using localhost with the port 587.

Using the Gmail account, we need to login to the Gmail account using Gmail user name and password. The smtplib provides the login() function which takes the username and password of the sender.

Sending an HTML using Python

When we try to send a text message using the Python, all content is treated as simple text.  If we include the HTML tags in a text message, it is treated as simple text and HTML tags will not be formatted according to HTML syntax. But Python allows an option to send an HTML message as actual HTML message.

While sending a message through e-mail, you can specify a Mime version, content type, and character set to send an HTML e-mail.

Facebooktwitterredditpinterestlinkedinmailby feather