Msg: Send messagesNote that the third parameter, msg is a string, indicating the mail. We know that an email generally consists of the title, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the msg Format. This format is defined in the smtp protocol.
InstanceThe following is a simple example of sending emails using Python:
#!/usr/bin/pythonimport smtplibsender = '[email protected]'receivers = ['[email protected]']message = """From: From Person
To: To Person
Subject: SMTP e-mail testThis 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"
Use Python to send HTML emailsThe difference between sending an HTML-format email in Python and sending a plain text message is to set _ subtype in MIMEText to html. The Code is as follows:
Import smtplib from email. mime. text import MIMEText mailto_list = ["[email protected]"] mail_host = "smtp.XXX.com" # Set server mail_user = "XXX" # username mail_pass = "XXXX" # password mail_postfix = "XXX.com" # The suffix def send_mail (to_list, sub, content): # to_list: recipient; sub: topic; content: mail content me = "hello" + "<" + mail_user + "@" + mail_postfix + ">" # Here, hello can be set at will. After receiving the mail, msg = MIMEText (content, _ subtype = 'html', _ charset = 'gb2312 ') # create an instance according to the settings, here, the message msg ['subobject'] = sub # sets the topic msg ['from'] = me msg ['to'] = ";". join (to_list) try: s = smtplib. SMTP () s. connect (mail_host) # connect to the smtp server s. login (mail_user, mail_pass) # log on to the server s. sendmail (me, to_list, msg. as_string () # Send email s. close () return True expect t Exception, e: print str (e) return False if _ name _ = '_ main _': if send_mail (mailto_list, "hello", "Xiao Wuyi"): print "sent successfully" else: print "failed to send"
Alternatively, you can specify the Content-type as text/html in the message body, as shown in the following example:
#!/usr/bin/pythonimport smtplibmessage = """From: From Person
To: To Person
MIME-Version: 1.0Content-type: text/htmlSubject: SMTP HTML e-mail testThis 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"
Python sends emails with attachmentsTo send an email with an attachment, you must first create a MIMEMultipart () instance, and then construct the attachment. If there are multiple attachments, You can construct them in sequence, and finally use smtplib. smtp to send the email.
From email. mime. text import MIMETextfrom email. mime. multipart import MIMEMultipartimport smtplib # create an instance with an attachment msg = MIMEMultipart () # construct the attachment 1att1 = MIMEText (open ('d: \ 123.rar ', 'rb '). read (), 'base64', 'gb2312') att1 ["Content-Type"] = 'application/octet-stream' att1 ["Content-Disposition"] = 'attachment; filename = "123.doc" '# Here, the filename can be written at will, what name is written, and what name is displayed in the email msg. attach (att1) # construct the attachment 2att2 = MIMEText (open ('d: \ 123.txt ', 'rb '). read (), 'base64', 'gb2312') att2 ["Content-Type"] = 'application/octet-stream' att2 ["Content-Disposition"] = 'attachment; filename = "123.txt" 'msg. attach (att2) # Add the mail header msg ['to'] = '[email protected] 'msg ['from'] =' [email protected] 'msg ['subobject'] = 'Hello world '# try: server = smtplib. SMTP () server. connect ('smtp .XXX.com ') server. login ('xxx', 'xxxxx') # XXX is the user name, And XXXXX is the password server. sendmail (msg ['from'], msg ['to'], msg. as_string () server. quit () print 'sent successfully 'failed t Exception, e: print str (e)
The following example specifies that the Content-type header is multipart/mixed and sends the/tmp/test.txt text file:
#! /Usr/bin/pythonimport smtplibimport base64filename = "/tmp/test.txt" # Read the file content and use base64 encoding fo = open (filename, "rb") filecontent = fo. read () encodedcontent = base64.b64encode (filecontent) # base64sender = '[email protected]' reciever = '[email protected]' marker = "AUNIQUEMARKER" body = "This is a test email to send an attachement. "# define the header information part1 =" From: From Person
To: To Person Subject: Sending AttachementMIME-Version: 1.0Content-Type: multipart/mixed; boundary = % s -- % s "% (marker, marker) # define the message action part2 = "Content-Type: text/plainContent-Transfer-Encoding: 8bit % s -- % s" % (body, marker) # define nearby parts of part3 = "Content-Type: multipart/mixed; name = \" % s \ "Content-Transfer-Encoding: base64Content-Disposition: attachment; filename = % s -- "% (filename, filename, encodedcontent, marker) message = part1 + part2 + part3try: smtpObj = smtplib. SMTP ('localhost') smtpObj. sendmail (sender, reciever, message) print "Successfully sent email" failed t Exception: print "Error: unable to send email"