I tried SMTP communication with Python

I had an opportunity to implement SMTP communication in Python, so I will write the implementation method.

When I was researching various implementation methods, I found a lot of information about implementing with the legacy API of the standard library, but I could not find much method with the currently recommended API. Django, a web framework, also uses legacy APIs, so I couldn't refer to the code of major libraries and frameworks. So, I implemented it while reading the code centering on the Python smtplib and ʻemail` standard libraries.

environment

Implementation details

  1. Establishing a connection with the SMTP server
  2. SMTP Auth
  3. Send email content
  4. Log the destinations that failed when sending to multiple destinations

Source code

import smtplib
from email.message import EmailMessage

class MailClient:
    def __init__(self, mail_data: Dict[str, Any] = {}) -> None:
        """
        Args:
            mail_data(Dict[]): Defaults to {}.
        """

        self._mail_data = mail_data

    def request(self) -> bool:
        """
        Returns:
            bool
        """

        with smtplib.SMTP(host=SMTP_HOST, port=int(SMTP_PORT)) as smtp:
            smtp.login(SMTP_USER, SMTP_PASSWORD)
            errors = smtp.send_message(self.message())

            if isinstance(errors, dict) and len(errors) > 0:
                logger.warn(
                    f'''Failed to send to all recipients.
                    Details: {errors}'''
                )

        return True

    def message(self) -> EmailMessage:
        msg = EmailMessage()
        msg['From'] = self._mail_data['from_address']
        msg['To'] = self._mail_data['to_address']
        msg['Subject'] = self._mail_data['subject']
        msg.set_default_type('text/plain')
        msg.set_content(self._mail_data['message'])

        bcc = self._mail_data.get('bcc')
        if bcc:
            msg['Bcc'] = convert_to_str(bcc)

        cc = self._mail_data.get('cc')
        if cc:
            msg['Cc'] = convert_to_str(cc)

        return msg

Commentary

request method

Start a connection with the SMTP server with smtplib.SMTP. If you are using TLS, use smtplib.SMTP_SSL, or make a connection in clear text and then usestarttls ()to connect with TLS. After successfully establishing the connection, authenticate with login (). Then send the data with send_message. It is sendmail that is actually responsible for sending data. Execute the SMTP command in this function to send an email. Regarding error handling, this time I didn't write try-except because I can simply raise if an exception occurs. However, when sending to multiple destinations, if even one fails, it is recorded as a log. That information is the return value of send_message and is stored in the ʻerrors` variable. The error type is Dict, the key is the destination address, and the value is a tuple containing the STMP response code and the corresponding message. If you want to know more about when send_message / sendmail returns a value, go to here There is a source code, so please read it.

message method

This time, the mail data is created using EmailMessage of the email module, but you can directly assign a character string to send_message or sendmail. However, we do not recommend it because it is difficult if you do not understand the protocol specifications. Use Email Message whenever possible.

in conclusion

I was planning to publish this article sooner, but I forgot to write it halfway, so it became like writing a blog (laughs). Have a nice year: snowman2:

Reference material

--smtplib --- SMTP Protocol Client

Recommended Posts

I tried SMTP communication with Python
I tried scraping with Python
I tried gRPC with Python
I tried scraping with python
I tried web scraping with python.
I tried running prolog with python 3.8.2.
I tried scraping Yahoo News with Python
I tried sending an email with python.
I tried non-photorealistic rendering with Python + opencv
I tried a functional language with Python
I tried recursion with Python ② (Fibonacci sequence)
#I tried something like Vlookup with Python # 2
Serial communication with Python
Socket communication with Python
Serial communication with python
I tried Python> autopep8
HTTP communication with Python
I tried Python> decorator
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
I tried "differentiating" the image with Python + OpenCV
I tried L-Chika with Raspberry Pi 4 (Python edition)
I tried Jacobian and partial differential with python
I tried to get CloudWatch data with Python
I tried function synthesis and curry with python
I tried to output LLVM IR with Python
I tried "binarizing" the image with Python + OpenCV
I tried running faiss with python, Go, Rust
I tried to automate sushi making with python
I tried playing mahjong with Python (single mahjong edition)
I tried running Deep Floor Plan with Python 3.6.10.
I tried to communicate with a remote server by Socket communication with Python.
I made blackjack with python!
I tried clustering with PyCaret
View Python communication with Fiddler
I tried Python C extension
[Python] I tried using OpenPose
I made blackjack with Python.
I made wordcloud with Python.
I tried to implement Minesweeper on terminal with python
I tried to touch the CSV file with Python
I tried to draw a route map with Python
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried to solve the soma cube with python
I tried to get started with blender python script_Part 02
I tried to automatically generate a password with Python3
Mayungo's Python Learning Episode 1: I tried printing with print
I tried to solve the problem with Python Vol.1
I tried to analyze J League data with Python
I tried "morphology conversion" of images with Python + OpenCV
I tried hitting the API with echonest's python client
I tried to solve AOJ's number theory with Python
I tried deploying Kubernetes Pods / Helm Chart with Pulumi (Python)
I tried to find the entropy of the image with python
I tried "gamma correction" of the image with Python + OpenCV
I tried to simulate how the infection spreads with Python
Socket communication with Python LEGO Mindstorms
I tried to make various "dummy data" with Python faker
I tried to touch Python (installation)
I tried sending an email from Amazon SES with Python
I tried trimming efficiently with OpenCV