Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to send email in python

Shulou Source: shulou.com Published: 2022-06-02 05:56:33 10月19日 Update

This article will explain in detail how to send emails in python. The quality of the article is high, so Xiaobian shares it with you as a reference. I hope you have a certain understanding of relevant knowledge after reading this article.

The first type: send mail normally, that is, send mail synchronously

#!/ usr/bin/env python

# -*- coding: utf-8 -*-

# @Time : 2019/8/14 10:14

# @Author : Andrew

# @Site :

# @File : send_mail.py

# @Software: PyCharm

from email.mime.text import MIMEText

import smtplib

from email.header import Header

from email.utils import parseaddr, formataddr #Set encoding format

from email.mime.multipart import MIMEMultipart

class SendMail:

def __init__(self):

#Define email address, password and SMTP server address

self.from_addr ='sender mailbox '

self.password = "pass" #Note that the password entered here is the protocol password set by yourself

self.to_addr = '*@126.com'

self.smtp_server = 'smtp.163.com'

def format_addr(self, s):

#Set username encoding to UTF-8

name, addr = parseaddr(s)

return formataddr((Header(name, 'utf-8').encode(), addr))

def msg_parse(self):

#Define the content of the message itself

msg = MIMEMultipart()

msg ['From '] = self.format_addr(f'sender')

msg ['To '] = self.format_addr(f'Receiver')

msg ['Subject '] = Header ('hhh, crawler error again, please fix', 'utf-8').encode()

#Define message body

msg.attach(MIMEText ('mail sent using python 3','plain',' utf-8'))

#Add attachments

# with open(r'C:\Users\Administrator\Desktop\test\test0.jpg', 'rb') as f:

# #Set MIME and file name of attachment, here is jpg type, can change png or other types:

# mime = MIMEBase('image', 'jpg', filename='test0.jpg')

# mime.add_header('Content-Disposition', 'attchment', filename='test0.jpg')

# mime.add_header('Content-ID', '')

# mime.add_header('X-Attachment-ID', '0')

# mime.set_payload(f.read())

# encoders.encode_base64(mime)

# msg.attach(mime)

server = smtplib.SMTP_SSL(self.smtp_server, 465)

# server.set_debuglevel(1)

server.login(self.from_addr, self.password)

server.sendmail(self.from_addr, [self.to_addr], msg.as_string())

server.quit()

if __name__ == '__main__':

SendMail().msg_parse()

Second: Send mail using asynchronous libraries

Note: This method requires the use of asynchronous library asyncio, which requires the use of time loops, that is, get_event_loop, which is the code written in main. If you restart the thread and send mail asynchronously, this will cause problems. You need to use new_event_loop to remember the following sentence:

The get_event_loop() method only works in the same thread, if in a new thread, you should use new_event_loop() to get the new loop and set it to the loop under that thread by setting it to set_event_loop(loop).

#!/ usr/bin/env python

# -*- coding: utf-8 -*-

# @Time : 2019/8/14 10:14

# @Author : Andrew

# @Site :

# @File : send_mail.py

# @Software: PyCharm

import asyncio

from email.mime.text import MIMEText

from email.utils import parseaddr, formataddr

from email.header import Header

import aiosmtplib

import logging

class SendMail:

def __init__(self):

#Define email address, password and SMTP server address

self.from_addr = '*@163.com'

self.password = "pass" #Note that the password entered here is the protocol password set by yourself

self.to_addr = '*@126.com'

self.smtp_server = 'smtp.163.com'

def format_addr(self, s): #Format address is also convenient to send Chinese

name, addr = parseaddr(s)

return formataddr((Header(name, 'utf-8').encode(), addr))

async def sendemail(self):

title = 'Dear %s, Hello:' % (

self.to_addr, self.to_addr)

tail = 'Crawler error, please fix the error in time'

html = title + tail

msg = MIMEText(html, 'html', 'utf-8')

msg ['From '] = self.format_addr ('From' % self.from_addr)

msg ['To '] = self.format_addr ('Dear Programmer' % self.to_addr)

msg ['Subject '] = Header ('fix bug',' utf-8').encode()

try:

async with aiosmtplib.SMTP(hostname=self.smtp_server, port=465, use_tls=True) as smtp:

await smtp.login(self.from_addr, self.password)

await smtp.send_message(msg)

except aiosmtplib.SMTPException as e:

logging.error('sendemail:%s' % e)

if __name__ == '__main__':

loop = asyncio.get_event_loop()

loop.run_until_complete(SendMail().sendemail())

The third type: use yagmail library to send mail, three lines of code to send mail

#!/ usr/bin/env python

# -*- coding: utf-8 -*-

# @Time : 2019/8/14 10:14

# @Author : Andrew

# @Site :

# @File : send_mail.py

# @Software: PyCharm

import yagmail

def send_mail(content):

yag = yagmail.SMTP(user='*@163.com', password='pass', host='smtp.163.com')

contents = [content] #Content

yag.send ('*@126.com','subject: fix', contents) About how to send emails in python to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Tags: Email address content password thread that is sender utf-8 dear code password article more server format body crawler knowledge article type Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Linux vpn Apple MySQL