Python divides email into two parts:
- Supports pop and SMTP.
- Support for email data.
Part 1: Use Pop and SMTP to read letters:
Import getpass, poplibm = poplib. POP3 ('localhost') M. user (getpass. getuser () M. pass _ (getpass. getpass () nummessages = Len (M. list () [1]) for I in range (nummessages): For J in M. RETR (I + 1) [1]:
Part 2: Data support:
- send common text Emails:
# import smtplib for the actual sending functionimport smtplib # import the email modules we ll needfrom email. mime. text import mimetext # open a plain text file for reading. for this example, assume that # The text file contains only ASCII characters. fp = open (textfile, 'rb') # create a text/plain messagemsg = mimetext (FP. read () FP. close () # Me = the sender's email address # You = the recipient's email addressmsg ['subobject'] = 'The contents of % s' % textfilemsg ['from'] = memsg ['to'] = you # send the message via our own SMTP server, but don't include the # envelope header. S = smtplib. SMTP () s. connect () s. sendmail (Me, [you], MSG. as_string () s. close ()
- send an email with an Image Attachment:
Import smtplib
# Module to be imported
From email. Mime. Image import mimeimage
From email. Mime. multipart import mimemultipart
Commaspace = ','
# Generate the required object
Email message. MSG = mimemultipart ()
MSG ['subobject'] = 'ur family reunion'
# Me = Source Address
# Family = address to be sent
MSG ['from'] = me
MSG ['to'] = commaspace. Join (family)
MSG. Preamble = 'ur family reunion'
# Pngfiles is a list of image file names.
For file in pngfiles:
# Open a file
# Automatic graph Detection
Fp = open (file, 'rb ')
IMG = mimeimage (FP. Read ())
FP. Close ()
MSG. Attach (IMG)
# Send via SMTP
S = smtplib. SMTP ()
S. Connect ()
S. Sendmail (Me, family, MSG. as_string ())
S. Close ()