Auto AdSense

Saturday, 24 January 2015

Python Programs - Sending Email using SMTP



  • Sending Email
    Simple Mail Transfer Protocol (SMTP) is a protocol which handles sending e-mail and routing e-mail between mail servers.
    Python provides smtplib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
    Syntax:
    import smtplib

    smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

    Here is the detail of the parameters:
    1. host: This is the host running your SMTP server. You can specifiy IP address of the host or a domain name. This is optional argument.
    2. port: If you are providing host argument then you need to specifiy a port where SMTP server is listening. Usually this port would be 25.
    3. local_hostname: If your SMTP server is running on your local machine then you can specify just localhost as of this option.
    An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message.
    It takes three parameters:
    1. The sender - A string with the address of the sender.
    2. The receivers - A list of strings, one for each recipient.
    3. The message - A message as a string formatted as specified in the various RFCs.
  • Example
    #!/usr/bin/python

    import smtplib

    sender = 'from@fromdomain.com'
    receivers = ['to@todomain.com']

    message = """From: From Person < from@fromdomain.com >
    To: To Person < to@todomain.com >
    Subject: SMTP e-mail test

    This is a test e-mail message.
    """

    try:
       smtpObj = smtplib.SMTP('localhost')
       smtpObj.sendmail(sender, receivers, message)
       print "Successfully sent email"
    except SMTPException:
       print "Error: unable to send email"

No comments:

Post a Comment