Pythonでメール受信

Pythonでメール受信して表示するスクリプト(text/plainのみ)。

#!/usr/bin/env python
# coding: utf-8
 
import poplib
import email
 
def get_subject(msg):
    h = email.Header.decode_header(msg.get('subject'))
    return unicode(email.header.make_header(h)).encode('utf-8')
 
def get_date(msg):
    mdate = email.utils.parsedate(msg.get('date'))
    return time.strftime('%Y/%m/%d %H:%M:%S', mdate)
 
def get_body(msg):
    body = msg.get_payload(decode=True)
    char = msg.get_param('charset')
    return unicode(body, char, 'ignore').encode('utf-8')
 
def main(popsv,user,passwd):
    # POP Connection
    m = poplib.POP3(popsv)
    m.user(user)
    m.pass_(passwd)
 
    # Loop for each mail
    for i in range(1,len(m.list()[1])+1):
        # Get a email
        msg = email.message_from_string('\n'.join(m.retr(i)[1]))
 
        # Get Subject
        subject = get_subject(msg)
 
        # Get Date
        mdate = get_date(msg)
 
        # Get Body
        body = get_body(msg)
 
        # Print E-Mail
        print('='*30)
        print('Subject: {0}'.format(subject))
        print('Date: {0}'.format(mdate))
        print('Body:\n{0}'.format(body))
 
        #m.dele(i)
 
    # POP Disconnection
    m.quit()
 
if __name__ == '__main__':
    popsv = '[your pop server]'
    user = '[your account]'
    passwd = '[your password]'
    main(popsv,user,passwd)