How to send emails in python

Source: Internet
Author: User
The email module in python makes it easier to process emails. This article mainly introduces the main methods for sending various emails in python. if you are interested, please take a look. The email module in python makes it easier to process emails. This article mainly introduces the main methods for sending various emails in python. if you are interested, please take a look.

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 classes include (for more details, see :#):

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", "Xiao Wuyi"): 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 ','
 
  
') 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 help you learn and support PHP.

For more details about the main methods for sending various emails in python, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.