Sending an e-mail using python code

This is a simple tutorial which will enable you to send an email using a simple python code.  The code is shown below.

python_mail

Each command of the above code is explained below

1: import “smtplib”

SMTP or simple mail transfer protocol is a protocol, which handles sending email and routing email between mail servers. “smtplib” is a native library in python and there is no need to install external libraries.

Python has “smtp” library which defines a SMTP client that can be used to send email to any internet machine.

2: server = smtplib.SMTP(‘host’, port)

Host: This is the host running your SMTP server. You can specify IP address of the host or a domain name like “gmail.com” or “yahoo.com”

Port: You have to specify the port where the “smtp” is listening. Usually the port is 587.

3: server.starttls()

This step is a security function to protect your password. “STARTTLS” is an extension to plain text communication protocols, which offers a way to upgrade a plain text connection to an encrypted (TLS or SSL) connection instead of using a separate port for encrypted communication.

4: server.login(“YOUR EMAIL ADDRESS”, “PASSWORD”)

Provide your email address and password in the required field. This is from where you send the email.

5: msg = “Subject: SMTP test mail

                This mail is send using python”

In the field provided for message type the required message to be sent.

6: server.sendmail(“YOUR EMAIL ADDRESS”, “RECEIPIENT’S EMAIL ADDRESS”, msg)

The senders and recipients email Ids are given in the required fields.

7: server.quit( )

          To disconnect from the server use this command.

The received email by using the above code will be as below.

pythonmail_2

Advertisements

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