Sending emails Python - Example program PDF

Title Sending emails Python - Example program
Author Anonymous User
Course Introduction to Computer Programming
Institution University of Canterbury
Pages 11
File Size 241.2 KB
File Type PDF
Total Downloads 100
Total Views 145

Summary

Example program...


Description

Python - Sending Email using SMTP 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. Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail − import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Here is the detail of the parameters −   

host − This is the host running your SMTP server. You can specify IP address of the host or a domain name like tutorialspoint.com. This is optional argument. port − If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25. 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 is typically used to do the work of mailing a message. It takes three parameters −   

The sender − A string with the address of the sender. The receivers − A list of strings, one for each recipient. The message − A message as a string formatted as specified in the various RFCs.

Example Here is a simple way to send one e-mail using Python script. Try it once − #!/usr/bin/python import smtplib sender = '[email protected]' receivers = ['[email protected]'] message = """From: From Person To: To Person 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"

Here, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mail requires a From, To, and Subject header, separated from the body of the e-mail with a blank line. To send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail). If you are not running an SMTP server on your local machine, you can use smtplib client to communicate with a remote SMTP server. Unless you are using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider must have provided you with outgoing mail server details that you can supply them, as follows − smtplib.SMTP('mail.your-domain.com', 25)

Sending an HTML e-mail using Python When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message. While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.

Example Following is the example to send HTML content as an e-mail. Try it once − #!/usr/bin/python import smtplib message = """From: From Person To: To Person MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format This is HTML message. This is headline. """ try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message)

print "Successfully sent email" except SMTPException: print "Error: unable to send email"

Sending Attachments as an E-mail To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens. Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.

Example Following is the example, which sends a file /tmp/test.txt as an attachment. Try it once − #!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Read a file and encode it into base64 format fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) sender = '[email protected]' reciever = '[email protected]'

# base64

marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From Person To: To Person Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # Define the message action part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body,marker)

# Define the attachment section part3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s %s --%s-""" %(filename, filename, encodedcontent, marker) message = part1 + part2 + part3 try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email" except Exception: print "Error: unable to send email"

Using Python to Send Email Python includes several modules in the standard library for working with emails and email servers.

smtplib Overview The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. SMTP stands for Simple Mail Transfer Protocol. The smtplib modules is useful for communicating with mail servers to send mail. Sending mail is done with Python's smtplib using an SMTP server. Actual usage varies depending on complexity of the email and settings of the email server, the instructions here are based on sending email through Gmail.

smtplib Usage This example is taken from this post at wikibooks.org """The first step is to create an SMTP object, each object is used for connection with one server.""" import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) #Next, log in to the server server.login("youremailusername", "password") #Send the mail

msg = " Hello!" # The /n separates the message from the headers server.sendmail("[email protected]", "[email protected]", msg) To include a From, To and Subject headers, we should use the email package, since smtplib does not modify the contents or headers at all.

Email Package Overview Python's email package contains many classes and functions for composing and parsing email messages.

Email Package Usage We start by only importing only the classes we need, this also saves us from having to use the full module name later. from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText Then we compose some of the basic message headers: fromaddr = "[email protected]" toaddr = "[email protected]" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Python email" Next, we attach the body of the email to the MIME message: body = "Python test mail" msg.attach(MIMEText(body, 'plain')) For sending the mail, we have to convert the object to a string, and then use the same prodecure as above to send using the SMTP server.. import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login("youremailusername", "password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text)

Verify an email address The SMTP protocol includes a command to ask a server whether an address is valid. Usually VRFY is disabled to prevent spammers from finding legitimate email addresses,but if it is enabled you can ask the server about an address and receive a status code indicating validity along with the user’s full name. This example is based on this post import smtplib server = smtplib.SMTP('mail') server.set_debuglevel(True) # show communication with the server try: dhellmann_result = server.verify('dhellmann') notthere_result = server.verify('notthere')

finally: server.quit() print 'dhellmann:', dhellmann_result print 'notthere :', notthere_result

Sending Mails using Gmail This example is taken from http://rosettacode.org/wiki/Send_an_email#Python import smtplib def sendemail(from_addr, to_addr_list, cc_addr_list, subject, message, login, password, smtpserver='smtp.gmail.com:587'): header = 'From: %s ' % from_addr header += 'To: %s ' % ','.join(to_addr_list) header += 'Cc: %s ' % ','.join(cc_addr_list) header += 'Subject: %s ' % subject message = header + message server = smtplib.SMTP(smtpserver) server.starttls() server.login(login,password) problems = server.sendmail(from_addr, to_addr_list, message) server.quit()

Example Usage of above script sendemail(from_addr to_addr_list cc_addr_list subject message login password

= = = = = = =

'[email protected]', ['[email protected]'], ['[email protected]'], 'Howdy', 'Howdy from a python function', 'pythonuser', 'XXXXX')

= = = = = = =

'[email protected]', ['[email protected]'], ['[email protected]'], 'Howdy', 'Howdy from a python function', 'pythonuser', 'XXXXX')

Sample Email Received sendemail(from_addr to_addr_list cc_addr_list subject message login password

Sources Python on Wikibooks.org Rosettacode.org Docs.python.org http://docs.python.org/2/library/email.mime.html

Recommended Python Training – DataCamp For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field. Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

Send Emails Using Python by Arjun Krishna Babu As a learning exercise, I recently dug into Python 3 to see how I could fire off a bunch of emails. There may be more straightforward methods of doing this in a production environment, but the following worked well for me. So, here’s a scenario: You have the names and email addresses of a bunch of contacts. And you want to send a message to each one of those contacts, while adding a “Dear [name]” at the top of the message. For simplicity’s sake you can store the contact details in a file rather than a database. You can also store the template of the message you wish to send in a file. The smtplib module of Python is basically all you need to send simple emails, without any subject line or such additional information. But for real emails, you do need a subject line and lots of information — maybe even pictures and attachments. This is where Python’s email package comes in. Keep in mind that it’s not possible to send an email message using the email package alone. You need a combination of both email and smtplib. Be sure to check out the comprehensive official documentation for both of these. Here are four basic steps for sending emails using Python: 1. Set up the SMTP server and log into your account. 2. Create the MIMEMultipart message object and load it with appropriate headers for From, To, and Subject fields. 3. Add your message body. 4. Send the message using the SMTP server object. Now let me walk you through the whole process. Let’s say you have a contacts file mycontacts.txt as follows: user@computer ~ $ cat mycontacts.txt john [email protected] katie [email protected]

Each line represents a single contact. We have the name followed by the email address. I’m storing everything in lowercase. I’ll leave it to the programming logic to convert any fields to upper-case or sentence-case if necessary. All of that is pretty easy in Python. Next, we have the message template file message.txt. user@computer ~ $ cat message.txt Dear ${PERSON_NAME}, This is a test message. Have a great weekend! Yours Truly

Notice the word “${PERSON_NAME}”? That is a template string in Python. Template strings can easily be replaced with other strings; in this example, ${PERSON_NAME} is going to be replaced with the actual name of the person, as you’ll see shortly. Now let’s start with the Python code. First up, we need to read the contacts from the mycontacts.txt file. We might as well generalize this bit into its own function. # Function to read the contacts from a given contact file and return a # list of names and email addresses def get_contacts(filename): names = [] emails = [] with open(filename, mode='r', encoding='utf-8') as contacts_file: for a_contact in contacts_file: names.append(a_contact.split()[0]) emails.append(a_contact.split()[1]) return names, emails The function get_contacts() takes a filename as its argument. It will open the file, read each line (i.e., each contact), split it into name and email, and then append them into two separate lists. Finally, the two lists are returned from the function. We also need a function to read in a template file (like message.txt) and return a Template object made from its contents. from string import Template def read_template(filename): with open(filename, 'r', encoding='utf-8') as template_file: template_file_content = template_file.read()

return Template(template_file_content) Just like the previous function, this one takes a filename as its argument. To send the email, you need to make use of SMTP (Simple Mail Transfer Protocol). As mentioned earlier, Python provides libraries to handle this task. # import the smtplib module. It should be included in Python by default import smtplib # set up the SMTP server s = smtplib.SMTP(host='your_host_address_here', port=your_port_here) s.starttls() s.login(MY_ADDRESS, PASSWORD) In the above code snippet, you’re importing the smtplib and then creating an SMTP instance that encapsulates an SMTP connection. It takes as parameter the host address and a port number, both of which entirely depends on the SMPT settings of your particular email service provider. For instance, in the case of Outlook, line 4 above would instead be: s = smtplib.SMTP(host='smtp-mail.outlook.com', port=587)

You should use the host address and port number of your particular email service provider for the whole thing to work. MY_ADDRESS and PASSWORD above are two variables that holds the full email address and

password of the account you’re going to use. Now would be a good time to fetch the contact information and the message templates using the functions we defined above. names, emails = get_contacts('mycontacts.txt') # read contacts message_template = read_template('message.txt')

Now, for each of those contacts, let’s send the mail separately. # import necessary packages from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # For each contact, send the email: for name, email in zip(names, emails): msg = MIMEMultipart() # create a message # add in the actual person name to the message template message = message_template.substitute(PERSON_NAME=name.title()) # setup the parameters of the message msg['From']=MY_ADDRESS msg['To']=email

msg['Subject']="This is TEST" # add in the message body msg.attach(MIMEText(message, 'plain')) # send the message via the server set up earlier. s.send_message(msg) del msg

For each name and email (from the contacts file), you’re creating a MIMEMultipart object, setting up the From, To, Subject content-type headers as a keyword dictionary, and then attaching the message body to the MIMEMultipart object as plain text. You might want to read the documentation to find out more about other MIME types you can experiment with. Also note that on line 10 above, I’m replacing ${PERSON_NAME} with the actual name extracted from the contacts file using the templating mechanism in Python. In this particular example I’m deleting the MIMEMultipart object and re-creating it each time you iterate through the loop. Once that is done, you can send the message using the handy send_message() function of the SMTP object you created earlier. Here’s the full code: import smtplib from string import Template from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText MY_ADDRESS = '[email protected]' PASSWORD = 'mypassword' def get_contacts(filename): """ Return two lists names, emails containing names and email addresses read from a file specified by filename. """ names = [] emails = [] with open(filename, mode='r', encoding='utf-8') as contacts_file: for a_contact in contacts_file: names.append(a_contact.split()[0]) emails.append(a_contact.split()[1]) return names, emails def read_template(filename): """ Returns a Template object comprising the contents of the file specified by filename. """ with open(filename, 'r', encoding='utf-8') as template_file:

template_file_content = template_file.read() return Template(template_file_content) def main(): names, emails = get_contacts('mycontacts.txt') # read contacts message_template = read_template('message.txt') # set up the SMTP server s = smtplib.SMTP(host='your_host_address_here', port=your_port_here) s.starttls() s.login(MY_ADDRESS, PASSWORD) # For each contact, send the email: for name, email in zip(names, emails): msg = MIMEMultipart() # create a message # add in the actual person name to the message template message = message_template.substitute(PERSON_NAME=name.title()) # Prints out the message body for our sake print(message) # setup the parameters of the message msg['From']=MY_ADDRESS msg['To']=email msg['Subject']="This is TEST" # add in the message body msg.attach(MIMEText(message, 'plain')) # send the message via the server set up earlier. s.send_message(msg) del msg # Terminate the SMTP session and close the connection s.quit() if __name__ == '__main__': main()

There you go! I believe the code is now fairly clear. Feel free to copy and tweak it as necessary. Apart from the official Python docs, I would also like to mention this resource which helped me a lot. Happy coding :) I originally published this article here. If you liked this article, please hit the small heart below. Thanks!...


Similar Free PDFs