Python send mail

A-L-Kun 2022-05-14 15:21:29 阅读数:938

pythonsendmail

Python Send E-mail

smtplib yes Python Module used to send mail ,email Is used to process mail messages

here , We use Decorator To make the function of sending mail

One 、 Text information

We use MIMEText To send text messages

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : mail.py
# @time : 2022/5/7 16:48
from smtplib import SMTP
from email.mime.text import MIMEText # The library used to send text messages 
from email.header import Header # Set the header information of the request 
from email.utils import formataddr # format 
from functools import wraps
receivers = ['[email protected]',] # The receiver is an iterative object , It can realize mass mailing 
subject = ' Test mail ' # Set the title of the message 
def decorate(fun_):
username = '[email protected]' # Sent by qq Number 
password_pass = 'meryyupicqjjciei' # Authorization code , Some mailboxes use login passwords 
smtp = SMTP('smtp.qq.com') # Create a SMTP The server , Use here qq mailbox 
smtp.login(username, password_pass) # Sign in 
@wraps(fun_)
def func_mail(*args, **kwargs):
fun_(smtp, username, *args, **kwargs) # Call the email function 
smtp.quit() # Shut down the server 
smtp.close()
return func_mail
@decorate
def mail(smtp, username):
for receiver_ in receivers:
msgRoot = MIMEText(f" This is a test email , Don't reply ~~~", "html", "utf-8") # If the second parameter is plain, Send a plain text message , If the email has Chinese , Then use utf-8
msgRoot["Subject"] = Header(subject, "utf-8") # Set text title 
msgRoot['From'] = formataddr(("A.L.Kun", username)) # Set sender information 
msgRoot['To'] = formataddr((receiver_.split("@")[0], receiver_)) # Set recipient information 
smtp.sendmail(username, receiver_, msgRoot.as_string()) # Send E-mail 
# smtp.set_debuglevel(1) # Output debugging information 
print(receiver_.split("@")[0], ': Send complete ')
if __name__ == '__main__':
mail()

The benefits of using decorators , You can dynamically create an object to send mail , At the same time, you can not pay attention to the configuration of mail , Just focus on the content of the email

Two 、 Image information

We can use MIMEImage To read picture data , Then send

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : mail.py
# @time : 2022/5/7 16:48
from smtplib import SMTP
from email.mime.text import MIMEText # The library used to send text messages 
from email.mime.multipart import MIMEMultipart # You can send many types of mail 
from email.mime.image import MIMEImage # Read picture information 
from email.header import Header
from email.utils import formataddr
from functools import wraps
import os
receivers = ['[email protected]',]
subject = ' Test mail '
pic_path = "./test.jpeg"
def decorate(fun_):
username = '[email protected]'
password_pass = 'mdsrecuicqjjciei'
smtp = SMTP('smtp.qq.com')
smtp.login(username, password_pass)
@wraps(fun_)
def func_mail(*args, **kwargs):
fun_(smtp, username, *args, **kwargs)
smtp.quit()
smtp.close()
return func_mail
@decorate
def mail(smtp, username):
for receiver_ in receivers:
msgRoot = MIMEMultipart("related") # Create a container , It can be for related Pattern , You can add text to it 、 picture 、 The attachment 
msgRoot["Subject"] = Header(subject, "utf-8")
msgRoot['From'] = formataddr(("A.L.Kun", username))
msgRoot['To'] = formataddr((receiver_.split("@")[0], receiver_))
pic_data = open(pic_path, "rb").read() # Read image data 
""" Send pictures as attachments """
send_img_f = MIMEImage(pic_data)
# Set header information , Both the first parameter and the second parameter represent sending as an attachment , The last one represents the file name of the file 
# As long as this header information is set , Is to send attachments 
send_img_f.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', os.path.basename(pic_path)))
msgRoot.attach(send_img_f) # Add a picture attachment to the container 
""" Add the picture to the text """
send_img_c = MIMEImage(pic_data)
# Set the unique identification of the picture , That's the picture id by img1, adopt `cid:img1` visit 
send_img_c.add_header("Content-Id", "<img1>")
msgRoot.attach(send_img_c) # First upload the image data to the container 
img_text = f""" <p> This is a picture :</p> <br><img src="cid:img1" width="300" alt={
os.path.basename(pic_path)}></br> """ # Use the imported picture data 
msgRoot.attach(MIMEText(img_text, "html", "utf-8"))
smtp.sendmail(username, receiver_, msgRoot.as_string())
print(receiver_.split("@")[0], ': Send complete ')
if __name__ == '__main__':
mail()

3、 ... and 、 The attachment

We use MIMEApplication To send attachments

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @author: A.L.Kun
# @file : mail.py
# @time : 2022/5/7 16:48
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.application import MIMEApplication # Send binary attachment 
from email.utils import formataddr
from functools import wraps
import os
receivers = ['[email protected]',]
subject = ' Test mail '
file_lis = ["./test2.pptx", "./test.jpeg"]
def decorate(fun_):
username = '[email protected]'
password_pass = 'mwdftrtycqjjciei'
smtp = SMTP('smtp.qq.com')
smtp.login(username, password_pass)
@wraps(fun_)
def func_mail(*args, **kwargs):
fun_(smtp, username, *args, **kwargs)
smtp.quit()
smtp.close()
return func_mail
@decorate
def mail(smtp, username):
for receiver_ in receivers:
msgRoot = MIMEMultipart("related") # Create a container , It has to be for related Pattern , You can add text to it 、 picture 、 The attachment 
msgRoot["Subject"] = Header(subject, "utf-8")
msgRoot['From'] = formataddr(("A.L.Kun", username))
msgRoot['To'] = formataddr((receiver_.split("@")[0], receiver_))
for file in file_lis:
# Create binary data 
msgFile = MIMEApplication(open(file, "rb").read())
# Set header 
msgFile.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', os.path.basename(file)))
# Add data to the container 
msgRoot.attach(msgFile)
smtp.sendmail(username, receiver_, msgRoot.as_string())
print(receiver_.split("@")[0], ': Send complete ')
if __name__ == '__main__':
mail()
版权声明:本文为[A-L-Kun]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141503511644.html