Teach you how to use Python to automatically send and receive emails

Teach you how to use Python to automatically send and receive emails

This article mainly introduces the method of automatically sending and receiving emails in Python. The sample code introduced in the article is very detailed. It has a certain reference value for everyone's study or work. Friends who need it, follow the teacher to learn

As a class representative, two things I often do are: helping to send homework and helping to receive homework, and most of the time it is done by mail. If you manually receive and send one by one, it will be a waste of time-life is too short , I use Python.

Go directly to the code and pull it to the end without knowing the details. I encapsulated it into two functions. According to the prompt, enter the parameters and call them directly. Pro-test is feasible

You can skip this part if you don't want to see the details, but you should paste this part in when you run it.

Import related libraries

import smtplib,ssl

from email.mime.multipart import MIMEMultipart

from email.mime.base import MIMEBase

from email.mime.text import MIMEText

from email.utils import formatdate

from email import encoders

import poplib

from email.parser import Parser

from email.header import decode_header

from email.utils import parseaddr

from email.header import Header

 

#Analyze the string in the message header, without this function, the header information will be garbled if printed out. Such as'=?gb18030?B?yrXWpL3hufsueGxz?=' This kind, through decode, it will be converted into Chinese

def decode_str(s):

value, charset = decode_header(s)[0]

if charset:

value = value.decode(charset)

return value

#Decoding the mail information is divided into two steps, the first is to take out the header information: first take the header information, mainly take out ['From','To','Subject']

def get_header(msg):

for header in ['From','To','Subject']:

value = msg.get(header,'')

if value:

if header =='Subject': #The title of the article has a special processing method

value = decode_str(value)

elif header in ['From','To']:

hdr, addr = parseaddr(value) #Address also has a special processing method

name = decode_str(addr)

value=name

print(header +':' + value)

#Header information has been taken out, get the character encoding of the mail, first look for the encoding in the message, if not, look for the Content-Type of the header

def guess_charset(msg):

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

#Mail body part: take the attachment, the body part of the mail is in the generator, msg.walk(), if there is an attachment, you can get the file name by way of .get_filename()

def get_file(path, msg):

for part in msg.walk():

filename=part.get_filename()

if filename!=None: #If there are attachments

filename = decode_str(filename) #The obtained file is a garbled name, decoded by the function defined at the beginning

data = part.get_payload(decode = True) #Remove the content of the file body

f = open(path+filename,'wb') #Here you can define the file save location by yourself

f.write(data)

f.close()

print('attachment', filename,'download successful')

def get_content(msg):

for part in msg.walk():

content_type = part.get_content_type()

charset = guess_charset(part)

if part.get_filename()!=None: #If there are attachments, skip directly

continue

email_content_type =''

content =''

if content_type =='text/plain':

email_content_type ='text'

elif content_type =='text/html':

print('html format skip')

continue #Don't email in html format

email_content_type ='html'

if charset:

try:

content = part.get_payload(decode=True).decode(charset)

except AttributeError:

print('type error')

except LookupError:

print("unknown encoding: utf-8")

if email_content_type =='':

continue #If the content is empty, also skip

print(email_content_type + '-----' + content)

# -------------------- Two functions for receiving and sending mail ---------------------- ----

def sent_email(from_addr,password, to_addrs,title,content,path=None):

'''

from_addr: sender email

password: sender password (if it is QQ or NetEase mailbox, write the authorization code here)

to_addrs: list of recipient mailboxes

title: email title

content: email content

path: If you need to send an attachment, fill in the path of the attachment here

'''

smtp_server ='smtp.'+ from_addr.split('@')[-1] # Sending server

msg = MIMEMultipart() # Create an empty email

msg['From'] = Header(from_addr) # add mail header information

msg['Subject'] = Header(title) # add mail title

msg.attach(MIMEText(content,'plain','utf-8')) # body content

if path != None:

# Add attachments

part = MIMEBase('application', "octet-stream")

part.set_payload(open(path, "rb").read()) # read attachment

encoders.encode_base64(part)

part.add_header('Content-Disposition','attachment', filename=path.split('/')[-1])

msg.attach(part) # Add attachments to the email

server = smtplib.SMTP_SSL(smtp_server) # Turn on the mailing service, where encrypted transmission is used

server.connect(smtp_server,465) # Login to send mail

for to_addr in to_addrs: # Traverse and send to each account

msg['To'] = Header(to_addr)

server.login(from_addr, password) # send mail

server.sendmail(from_addr, to_addr, msg.as_string())

server.quit() # Close the server

print('Send successfully')

def get_email(email,password,path):

'''

email: Email address

password: password (if it is QQ mailbox or NetEase mailbox, fill in the authorization code here)

path: The location where the attachment is kept

'''

server=poplib.POP3_SSL('pop.'+email.split('@')[-1]) #Modify the corresponding mailbox server

server.user(email)

server.pass_(password)

resp, mails, octets = server.list() #Login process

index = len(mails) #Total number of mails

resp, lines, octets = server.retr(index) #Read the most recent mail

msg_content = b'\r\n'.join(lines).decode('utf-8','ignore')

msg = Parser().parsestr(msg_content)

#server.dele(index) Delete mail

get_header(msg) # Display mail information, including sender, recipient, and title

get_file(path,msg) # keep attachments

get_content(msg) # Display file content

server.quit()

print('Received successfully')

Just look here!

1. Send mail function: sent_email(from_addr, password, to_addrs, title, content, path=None)

Enter the parameters in brackets in order

from_addr: sender email

password: sender password (if it is QQ or NetEase mailbox, write the authorization code here)

to_addrs: list of recipient mailboxes

title: email title

content: email body content

path: If you need to send an attachment, fill in the path of the attachment here, if not, just ignore it

from_addr = '20182*****@mail.scut.edu.cn' # Type a code, and enter your own email address here

password ='scut_827*****' # Enter your password (if it is qq or NetEase mailbox, enter the authorization code here)

to_addrs = ['lly****@163.com', '12375947@qq.com'] # write the email address to be sent here

title ='This is a test email' # title of the email

content ='Just write something' # body content

path ='C:/Users/File to be sent.xlsx' # If you want to send an email with attachments, then fill in your attachment path here

sent_email(from_addr, password, to_addrs, title, content, path) # send email

2. Receiving mail function: get_email(email, password, path)

email: Email address

password: password (if it is QQ mailbox or NetEase mailbox, fill in the authorization code here)

path: The location where the attachment is kept

email = '1234567@163.com' # Fill in your email account (the email address you want to receive emails from)

password ='LXSHS*****' # Fill in your email password (if it is qq or NetEase email, enter authorization here

path ='C:/Users/Desktop/' # If the other party's email has attachments, the attachments will be downloaded here

get_email(email,password,path)

So far, this article on the method of automatically sending and receiving emails in Python is introduced. For more related Python automatic sending and receiving email content, please search our previous articles or continue to browse related articles below. Hope you will support us a lot in the future. !

Reference: https://cloud.tencent.com/developer/article/1689792 teaches you how to use Python to automatically send and receive emails-Cloud + Community-Tencent Cloud