Describes the main methods for sending various types of emails in python and how to send emails in python.
The email module in python makes it easier to process emails. Today, I have learned the specific method of sending emails. Here I will write my own experiences. Please give me some advice.
I. Introduction to related modules
The smtplib and email modules are used to send emails. Here we will give a brief introduction to the two modules:
1. smtplib Module
Smtplib. SMTP ([host [, port [, local_hostname [, timeout])
SMTP constructor indicates a connection with the SMTP server. Through this connection, you can send commands to the smtp server to execute relevant operations (such as login and email sending ). All parameters are optional.
Host: smtp server host name
Port: the smtp service port. The default value is 25. If the two parameters are provided when an SMTP object is created, the connect method is automatically called during initialization to connect to the server.
The smtplib module also provides SMTP_SSL and LMTP classes, which are basically the same as SMTP.
Methods provided by smtplib. SMTP:
SMTP. set_debuglevel (level): sets whether the debug mode is used. The default value is False, that is, non-debug mode, indicating that no debugging information is output.
SMTP. connect ([host [, port]): connect to the specified smtp server. The parameters represent the smpt host and port respectively. Note: You can also specify the port number (for example, smpt.yeah.net: 25) in the host parameter so that the port parameter is unnecessary.
SMTP.doc md (cmd [, argstring]): sends commands to the smtp server. The optional parameter argstring indicates the command parameter.
SMTP. helo ([hostname]): use the "helo" command to confirm the identity of the server. It is equivalent to telling the smtp server "who I am ".
SMTP. has_extn (name): determines whether the specified name exists in the server email list. For security reasons, smtp servers often block this command.
SMTP. verify (address): determines whether the specified email address exists on the server. For security reasons, smtp servers often block this command.
SMTP. login (user, password): log on to the smtp server. Currently, almost all smtp servers must verify that the user information is valid before sending emails.
SMTP. sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options]): send an email. Note 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.
SMTP. quit (): disconnect from the smtp server, which is equivalent to sending the "quit" command. (Smtp. close () is used in many programs. The difference between it and quit is fixed by google, and no answer is found .)
2. email Module
The emial module is used to process mail messages, including MIME and other RFC 2822-based message documents. Using these modules to define mail content is very simple. Its included classes are (more detailed introduction visible: http://docs.python.org/library/email.mime.html ):
Class email. mime. base. MIMEBase (_ maintype, _ subtype, ** _ params): This is a base class of MIME. Generally, you do not need to create an instance when using it. Among them, _ maintype is the content type, such as text or image. _ Subtype is the minor type of the content, such as plain or gif. ** _ Params is a dictionary that is passed directly to Message. add_header ().
Class email. mime. multipart. MIMEMultipart ([_ subtype [, boundary [, _ subparts [, _ params]: A subclass of MIMEBase, a set of multiple MIME objects. The default value of _ subtype is mixed. Boundary is the boundary of the MIMEMultipart. The default boundary is only a handful.
Class email. mime. application. MIMEApplication (_ data [, _ subtype [, _ encoder [, ** _ params]): a subclass of MIMEMultipart.
Class email. mime. audio. MIMEAudio (_ audiodata [, _ subtype [, _ encoder [, ** _ params]): MIME audio object
Class email. mime. image. MIMEImage (_ imagedata [, _ subtype [, _ encoder [, ** _ params]): MIME binary file object.
Class email. mime. message. MIMEMessage (_ msg [, _ subtype]): use the following method for a specific message instance:
Msg = mail. message. message () # An Instance msg ['to'] = 'xxx @ XXX.com '# where to send msg ['from'] = 'yyy @ YYYY.com' # your email address msg ['date'] = '1970-3-16' # Date and Time msg ['subobject'] = 'Hello world' # subject
Class email. mime. text. MIMEText (_ text [, _ subtype [, _ charset]): MIME text object, where _ text is the mail content and _ subtype is the mail type, it can be text/plain (plain text mail), html/plain (html mail), _ charset encoding, or gb2312.
II. Specific implementation code of several emails
1. common text emails
To implement normal text mail, SET _ subtype in MIMEText to plain. First, import smtplib and mimetext. Create an smtplib. smtp instance, connect the smtp server, and send it after login. The Code is as follows: (implemented in python2.6)
#-*-Coding: UTF-8-*-''' send txt text mail ''' import smtplib from email. mime. text import MIMEText mailto_list = [YYY@YYY.com] mail_host = "smtp.XXX.com" # Set server mail_user = "XXXX" # username mail_pass = "XXXXXX" # password mail_postfix = "XXX.com" # suffix def of the sender send_mail (to_list, sub, content): me = "hello" + "<" + mail_user + "@" + mail_postfix + ">" msg = MIMEText (content, _ subtype = 'plain ', _ charset = 'gb2312') msg ['subobject'] = sub msg ['from'] = me Msg ['to'] = ";". join (to_list) try: server = smtplib. SMTP () server. connect (mail_host) server. login (mail_user, mail_pass) server. sendmail (me, to_list, msg. as_string () server. close () return True expect t Exception, e: print str (e) return False if _ name _ = '_ main _': if send_mail (mailto_list, "hello", "hello world! "): Print" sent successfully "else: print" failed to send"
2. html mail sending
Unlike text mail, the _ subtype in MIMEText is set to html. The Code is as follows: (implemented in python2.6)
#-*-Coding: UTF-8-*-''' sends an html text email ''' import smtplib from email. mime. text import MIMEText mailto_list = ["YYY@YYY.com"] mail_host = "smtp.XXX.com" # Set server mail_user = "XXX" # username mail_pass = "XXXX" # password mail_postfix = "XXX.com" # sender's 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", "<a href = 'HTTP: // www.cnblogs.com/xiaowuyi'> Xiao Wuyi </a>"): print "sent successfully" else: print "failed to send"
3. Send emails with attachments
To 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.
#-*-Coding: cp936-*-''' send an email with an attachment ''' 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'] = 'yyy @ YYY.com 'msg ['from'] = 'xxx @ XXX.com' msg ['subobject'] = 'Hello world '# send email 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)
4. Use MIMEimage to send images
#-*-Coding: cp936-*-import smtplibimport mimetypesfrom email. mime. text import MIMETextfrom email. mime. multipart import MIMEMultipartfrom email. mime. image import MIMEImagedef AutoSendMail (): msg = MIMEMultipart () msg ['from'] = "XXX@XXX.com" msg ['to'] = "YYY@YYY.com" msg ['subobject'] = "hello world" txt = MIMEText ("this is a Chinese mail content Oh ", 'plain ', 'gb2312') msg. attach (txt) file1 = "C: \ hello.jpg" image = MIMEImage (open (file1, 'rb '). read () image. add_header ('content-id', '<image1>') msg. attach (image) server = smtplib. SMTP () server. connect ('smtp .XXX.com ') server. login ('xxx', 'xxxxxx') server. sendmail (msg ['from'], msg ['to'], msg. as_string () server. quit () if _ name _ = "_ main _": AutoSendMail ()
I used MIMEimage to send images. I originally wanted to display the images in the body. However, after the code is run, I found that the images are still sent as attachments. I hope some experts can give me some advice, how can I send an email that shows the image in the body, that is, the image exists in the attachment but can be displayed in the body at the same time. The specific form is as follows.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.