Python System Management _ 09_python_email Processing

Source: Internet
Author: User

EmailResolution:

Contains header and body:

Header contains control data:

The title of the sender, destination, and information,

Body contains information.

The following are the headers used by the mail program:

1. The From header can indicate the sender of the email to the user. It is often used when the customer clicks the "reply" button. The new email is sent to the address in Form header:

2. Reply-To header:

3. The Subject header is used to display the mailbox abstract.

4. Date header can be used to classify email addresses by arrival time;

5. Message-ID and In-Reply-To header can help some mail programs implement thread and arrange mail In different levels );

6. The MIME header can help the mail program to display the mail in a proper language and format. They are also used to process attachments.

General instance: trad_gen_simple.py

#!/usr/bin/env python#Traditional Message Generation , Simple#Trad_gen_simple.pyfrom email.MIMEText import MIMETextmessage = ''' Hello,This is a test message form Traditional Message!-- Anonymous '''msg = MIMEText(message)msg['To'] = 'recipient@example.com'msg['From'] = 'Test Sender <sender@example.com>'msg['Subject'] = 'Test Message ,'print msg.as_string()


Add Date and Message-ID header

Date header is a format specially set for E-mail. It is generated by the email. Utils. formatdate () function.

Add a Message-ID header for the new mail, and the Message-ID does not repeat the Message-ID of other emails in the world. The function is generated: email. Utils. make_msgid ()

Instance: trad_gen_newhdrs.py

#!/usr/bin/env python#Traditional Message Generation with Date and Message-ID#Trad_gen_newhdrs.pyfrom email.MIMEText import MIMETextfrom email import Utilsmessage = ''' Hello,This is a test message form Traditional Message!-- Anonymous '''msg = MIMEText(message)msg['To'] = 'recipient@example.com'msg['From'] = 'Test Sender <sender@example.com>'msg['Subject'] = 'Test Message ,'msg['Date'] = Utils.formatdate(localtime = 1)msg['Message-ID'] = Utils.make_msgid()print msg.as_string()

In this way, the email can be sent.


Parse traditional Emails:

Edit the generated file message.txt as the text to be parsed.

Edit trad_parse.py as the parsing program.

Iterates the mail Information and retrieves necessary information.


Resolution Date:

It is not easy to parse the Date from E-mail. The header contains the Date identification method, and the actual Date header may be invalid. Despite the python emai. Utils module. Parsedate_tz) function will load a date string, you want to return 10 elements of the tuples, 9 elements of the tuples can be passed to time. mktime () 10th specifies the time zone, and mktime () cannot receive it. Therefore, the mktime_tz () function can be used to convert this special 10th element.

Example of a parsing program: data_parse.py

#!/usr/bin/env python#Traditional Message Parsing#data_parse.pyimport sys, email, timefrom email import Utilsdef getdate(msg):    """Returns the date/time from msg in seconds-since-epoch, if possible.    Otherwise,returens None."""    if not 'date' in msg:        #No Date header present.        return None    datehdr = msg['date'].strip()    try :    print Utils.mktime_tz(Utils.parsedate_tz(datehdr))        return Utils.mktime_tz(Utils.parsedate_tz(datehdr))    except:        # Some sort of error occured, like ly because of an invalid date.        return Nonemsg = email.message_from_file(sys.stdin)dateval = getdate(msg)if dateval is None:    print "No valid date was found."else:    print "dateval:" , dateval

MIME concept:

MIME contains multiple parts. A regular mail contains headers and content. When you use MIME for multiple parts of the mail, you can include text and attachments, for example. It can be used in different ways, such as plain text and HTML ).

MIME supports different transmission encodings and provides content types such as text, plainimage, and jpeg. character sets can be specified.


How MIME works:

According to the General Convention, the most basic content is plain text mail,) will appear at the beginning, so that no MIME programs can also read, Python can be used to parse the tree.


Add MIME attachment:

To write emails with attachments, You need to perform the following steps:

1. Create a MIMEMultipart () object and set the mail header.

2. Create a MIMEText () object for the mail content and put it into the MIMEMultipart () object.

3. Create a suitable MIME object for each attachment and put it into the MIMEMultpart () object.

4. Call the as_string () function in the MIMEMultipart () object to obtain the mail as a result.

Demo: mime_gen_basic.py

#!/usr/bin/env python# MIME attachement generation# mime_gen_basic.pyfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEBase import MIMEBasefrom email import Utils, Encodersimport mimetypes, sysdef attachment(filename):    fd = open(filename,'rb')    mimetype, mimeencoding = mimetypes.guess_type(filename)    if mimeencoding or (mimetype is None):        mimetype = 'application/octet-stream'    maintype, subtype = mimetype.split('/')    if maintype == 'text':        retval = MIMEText(fd.read(),_subtype=subtype)    else:        retval = MIMEBase(maintype, subtype)        retval.set_payload(fd.read())        Encoders.encode_base64(retval)    retval.add_header('Content-Disposition','attachment',filename = filename)    fd.close()    return retvalmessage = ''' Hello,This is a test message form Traditional Message!-- Anonymous '''msg = MIMEMultipart()msg['To'] = 'recipient@example.com'msg['From'] = 'Test Sender <sender@example.com>'msg['Subject'] = 'Test Message ,'msg['Date'] = Utils.formatdate(localtime = 1)msg['Message-ID'] = Utils.make_msgid()body = MIMEText(message,_subtype='plain')msg.attach(body)for filename in sys.argv[1:]:    msg.attach(attachment(filename))print msg.as_string()


SMTPSend Email:

Python implements SMTP through the smtplib module. It is easier for the smtplib module to use SMTP simple tasks.

Simple SMTP program: smtp_simple.py

SMTP sends an email with an attachment:

Mime_stmp.py

#!/usr/bin/env python# MIME attachement generation# mime_gen_basic.pyfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEBase import MIMEBasefrom email import Utils, Encodersimport mimetypes, sysimport smtplibmail_server = 'smtp.exmail.qq.com'mail_server_port = 465from_addr = 'test@x'to_addr = 'x's=smtplib.SMTP_SSL(mail_server,mail_server_port)def attachment(filename):    fd = open(filename,'rb')    mimetype, mimeencoding = mimetypes.guess_type(filename)    if mimeencoding or (mimetype is None):        mimetype = 'application/octet-stream'    maintype, subtype = mimetype.split('/')    if maintype == 'text':        retval = MIMEText(fd.read(),_subtype=subtype)    else:        retval = MIMEBase(maintype, subtype)        retval.set_payload(fd.read())        Encoders.encode_base64(retval)    retval.add_header('Content-Disposition','attachment',filename = filename)    fd.close()    return retvalmessage = ''' Hello,This is a test message form Traditional Message!

POP3 receive mail:

The process of connecting and authenticating a remote server:

1. Create a POP3 object and send it to the host name and port number of the remote server.

2. Call the user () and pass _ () functions to send the user name and password.

3. If a poplib. error_proto exception occurs, the server fails to log on and sends the exception-related strings and explanatory text.

4. Once connected, call stat () to return a single tuple, which contains the number of emails in the server mailbox and the total size of emails.

5. Call quit () to disable the POP connection. The Code is as follows:


A simple connection: POP3_simple.py

#!/usr/bin/env python#pop3_simple.pyimport poplibusername='test@x'password='x'mail_server = 'xx'p = poplib.POP3(mail_server)p.user(username)p.pass_(password)status = p.stat()print "Mailbox has %d messages for a total of %d bytes" %(status[0],status[1])p.quit()#for msg_id in p.list()[1]:#    print msg_id#    outf = open ('%s.eml' % msg_id , 'w')#    outf.write('\n' .join(p.retr(msg_id)[1]))#    outf.close()#p.quit()

Get email information: pop3_get.py

#!/usr/bin/env python#pop3_get.pyimport poplibusername='test@x'password='x'mail_server = 'pop.exmail.qq.com'p = poplib.POP3(mail_server)p.user(username)p.pass_(password)status = p.stat()print "Mailbox has %d messages for a total of %d bytes" %(status[0],status[1])for item in p.list()[1]:    print item    print item.split(' ')    number, octets = item.split(' ')    print "Message %s: %s bytes " %(number,octets)p.quit()#for msg_id in p.list()[1]:#    print msg_id#    outf = open ('%s.eml' % msg_id , 'w')#    outf.write('\n' .join(p.retr(msg_id)[1]))#    outf.close()#p.quit()

Download Email: pop3_download.py

#!/usr/bin/env python#pop3_download.pyimport poplibimport getpass,sys,emailusername='test@x'password='x'mail_server = 'pop.exmail.qq.com'dest = "testmbox"#destfd = open (dest,"at")p = poplib.POP3(mail_server)p.user(username)p.pass_(password)status = p.stat()print "Mailbox has %d messages for a total of %d bytes" %(status[0],status[1])for item in p.list()[1]:#    print item#    print item.split(' ')    number, octets = item.split(' ')    print "Message %s: %s bytes " %(number,octets)    # Retrieve the message (storing it in a list of lines)    lines = p.retr(number)[1]    print lines    print "*" * 75    #Create an e-mail object representing the message    msg = email.message_from_string("\n" .join(lines))    print msg    destfd = open('%s.eml'%number,"at")    #Write it out to the mailbox    destfd.write(msg.as_string(unixfrom=1))    # Make sure there's an extra newline separating messages    destfd.write("\n")p.quit()destfd.close()#for msg_id in p.list()[1]:#    print msg_id#    outf = open ('%s.eml' % msg_id , 'w')#    outf.write('\n' .join(p.retr(msg_id)[1]))#    outf.close()#p.quit()

Delete Email: L


This article is from the "fzhaolei" blog, please be sure to keep this source http://53254.blog.51cto.com/43254/1334631

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.