Send and Receive mail with Python

1. Send Mail:

import smtplib
import email.mime.multipart as multipart
from email.mime.text import MIMEText as mimetext

def send_mail(content):
    sender = '[email protected]'
    to_receiver = ','.join(['[email protected]', '[email protected]'])
    cc_receiver = ','.join(['xxx', 'xxx'])
    msg_subject = 'xxx Daily Report (%s)' % current_day
    output = content

    msg =  multipart.MIMEMultipart()
    msg.add_header('From',sender)
    msg.add_header('To',to_receiver)
    msg.add_header('CC', cc_receiver)
    msg.add_header('Subject',msg_subject)
    body = multipart.MIMEMultipart('altrnative')
    #body.attach(mimetext(output.encode('utf-8'),'txt','utf-8'))
    body.attach(mimetext(output))
    msg.attach(body)

    smtpObj = smtplib.SMTP('smtp.filemaker.com')
    smtpObj.sendmail(sender,to_receiver,msg.as_string())
    #smtpObj.send_message(msg)
    smtpObj.quit()

2. Receive mail with imap:

Import imaplib

def receive_email_to_individual_imap():
    username = 'xxx'
    passwd = 'xxx'
    imap_server = 'mail.xxx.com'
    conn = False
    try:
        conn = imaplib.IMAP4_SSL(imap_server,993)
    except Exception as e:
        print('fail to connect to mail server')
        print(e)
    if conn:
        try:
            print('Connected to mail server')
            conn.login(username,passwd)
            conn.select("INBOX")
            #conn.search() returns a turple with two item: (type, data)
            #type: a string indicate that search is fail or OK
            #data: a list with only 1 item,  which is a string of mailID list separated by space
            #for example ('OK', [b'197 198 199 200 201 202 204 205 206 207 208 209 210 211 212 213'])
            type, data = conn.search(None, '(SUBJECT "Test email sending")')

            print(type)
            print(data)
            msglist = data[0].split() 
            print(msglist)
            print(msglist[0])
            # conn.fetch(mailID, '(RFC822)') returns a turple with two item: (type, maildata)
            # type: a string indicate that fetch is fail or OK
            # maildata: a list with two items: maildata[0], and maildata[1]
            # maildata[0]: a tuple with two items: maildata[0][0] and maildata[0][1]
            # maildata[0][0]: a string with mailID and RFC: for example: b'197 (RFC822 {3863}'
            # maildata[0][1]: a string which is the binary of the mail contents
            # maildata[0][1] example:  b'Received: from mr2-mtap-s02.rno.apple.com ([192.168.0.113])......'
            # maildata[0][1].decode(): decode the mail conent to txt
            type, mail_content =  conn.fetch(msglist[0],'(RFC822)')
            print (mail_content)
            print (mail_content[0][1].decode())
        except Exception as e:
            print(e)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章