python mail service

    First, log in to the mail client to set up, enable the SMTP and POP services of the mail, and generate an authorization code, so that the authorization code is used instead of the password to log in when programming.

    Receive mail SMTP

#! /usr/bin/env python
#coding=utf-8
from smtplib import SMTP as smtp,SMTPException as se
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

HOST="smtp.163.com" #Server
USER="[email protected]" #User
PASSWD="XXX" #authorization code
SENDOR="[email protected]" #Sender
RECEPTOR="[email protected],"+SENDOR #Receiver

message=MIMEMultipart("relate") #Multiple types of messages

message["From"]=SENDOR
message["To"]=RECEPTOR
message["Cc"]=SENDOR
message["Subject"]=Header("This is a python mail test with attachments","utf-8") #For Chinese, use Header's utf-8 encoding
#The above properties must be strings
thebody=MIMEText("python send mail test","plain","utf-8")
message.attach(thebody) #Add the body text content
att=MIMEText(open('/home/test5_2.c','rb').read(),'base64','utf-8')
att['Content-Disposition']="attchment;filename=test.c" #Attachment description, do not enclose the file name with single quotes
message.attach(att) #Add attachment
try:
    s=smtp()
    s.connect(HOST,25) #Connect to the server
    s.login(USER,PASSWD) #login
    s.sendmail(SENDOR,RECEPTOR.split(","),message.as_string()) #Send mail, pay attention to parsing the string RECEPTOR into a tuple or list, message.as_string is more critical
    print "Mail sent successfully"
except se:
    print "Error: unable to send file"
    s.quit()
s.quit()


read mail POP3

#coding=utf-8
from poplib import POP3
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr

POP3SVR="pop3.163.com"

recvSvr=POP3(POP3SVR)
print recvSvr.getwelcome()

recvSvr.user('[email protected]')
recvSvr.pass_('XXX')

print "Message: %s. Size: %s\n" % recvSvr.stat()

resp,mails,octets=recvSvr.list() #List all mail returned information, total list of information, total size of information
index=len(mails) #Get the last email subscript
rsp,lines,siz=recvSvr.retr(index) #Get the return information of the specified email, specify the list of all lines of the email information, and specify the size of the email
msg_content='\n'.join(lines) # Convert the list of all lines of information into strings
msg=Parser().parsestr(msg_content) #parse the string into Message type
recvSvr.quit() #Log out

def print_info(msg,indent=0):
    printLine=False
    if indent==0: #If this function is called for the first time, first print out the three major attributes of message From, To, Subject
        for header in ['From','To','Subject']:
            value=msg.get(header,'') #Use the get method
            if value:
                if header=='Subject':#decoding conversion
                    value=decode_str(value)
                else: #If it is the recipient and the sender, the email address must be parsed and then decoded and converted
                    hdr,addr=parseaddr(value)
                    name=decode_str(hdr)
                    value='%s <%s>' % (name,addr)
            print("%s%s: %s" % (' '*indent,header,value))
            if header=="Subject":
                print "body:"
    if msg.is_multipart(): #Called after the second time, if the message contains multiple different types of information
        parts=msg.get_payload() #Get all the different types of information
        for n,part in enumerate(parts): #Iterate various information
            print_info(part,indent+1) #recursive
    else: #When the multi-type is decomposed into a single type, it is processed here
        content_type=msg.get_content_type() #Get the type of information
        if content_type=='text/plain' or content_type=='text/html': #If it is text information or html format information
            content=msg.get_payload(decode=True) #Get information and allow decoding
            charset=guess_charset(msg) #Get the encoding format of the message itself
            if charset:
                content=content.decode(charset) #decode with utf-8
            print "%sText: %s" % (' '*indent,content+'...')
        else: #if it is an attachment
            if not printLine:
                print "-"*10
                printLine = not printLine
            print "%sAttachment: %s" % (' '*indent,content_type) #Print directly


def decode_str(s): #appropriate decoding
    value,charset=decode_header(s)[0]
    if charset:
        value=value.decode(charset)
    return  value

def guess_charset(msg): #self encoding
    charset=msg.get_charset()
    if charset is None:
        content_type=msg.get('Content-Type','').lower()
        pos=content_type.find('charset=')
        if pos>=0:
            charset=content_type[pos+8:].strip()
    return charset

print_info(msg)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325659367&siteId=291194637