Sending Email Using SMTP
mMessage = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To, Date, Subject, Text)) s = smtplib.SMTP('mail.sfcn.org') rCode = s.sendmail(From, To, mMessage) s.quit()
The smtplib module included with Python provides simple access to SMTP servers that allow you to connect and quickly send mail messages from your Python scripts.
Mail messages must be formatted properly for the To, From, Date, Subject, and text fields to be processed properly by the SMTP mail server. The code in send_smtp.py shows the proper formatting for the mail message, including the item headers and newline characters.
Once the mail message is properly formatted, connect to the SMTP server using the smtplib.SMTP(host [,port]) method. If it is necessary to log in to the SMTP server, use the login(user, password) method to complete an authentication.
Once connected to the SMTP server, the formatted message can be sent using sendmail(from, to, message), where from is the sending email address string, to specifies a list of destination email address strings, and message is the formatted message string.
After you are finished sending messages, use the quit() method to close the connection to the SMTP server.
import smtplib import time From = "bwdayley@sfcn.org" To = ["bwdayley@novell.com"] Date = time.ctime(time.time()) Subject = "New message from Brad Dayley." Text = "Message Text" #Format mail message mMessage = ('From: %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To, Date, Subject, Text)) print 'Connecting to Server' s = smtplib.SMTP('mail.sfcn.org') #Send mail rCode = s.sendmail(From, To, mMessage) s.quit() if rCode: print 'Error Sending Message' else: print 'Message Sent Successfully'
send_smtp.py
Connecting to Server Message Sent Successfully
Output from send_smtp.py code
Also, see Figure 7.1.
Figure 7.1 Email message sent by send_smtp.py code.