Skip to content

Instantly share code, notes, and snippets.

@iamunr4v31
Created August 14, 2021 11:51
Show Gist options
  • Save iamunr4v31/a21a2f09be010ed4cc1f202c17f4b104 to your computer and use it in GitHub Desktop.
Save iamunr4v31/a21a2f09be010ed4cc1f202c17f4b104 to your computer and use it in GitHub Desktop.
Sending mail through amazon SES
import os
import boto3
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
from html import unescape
from service.response import Response
from email.utils import formataddr
class SESMail(SESConfig):
def __init__(self, recipient: List, subject: str, body_html: str,
filename: str) -> None:
self.recipient: List = recipient
self.subject: str = subject
self.html_body: str = body_html
self.filename: str = filename
def __repr__(self) -> str:
return (f'SENDER: {self.sender_name}\nRECIPIENT: {self.recipient}\n'
f'SUBJECT: {self.subject}\nMESSAGE: {self.text_body}')
def _html_to_text(self, html: str) -> str:
soup = BeautifulSoup(html, 'lxml')
return unescape(soup.get_text())
def _preprocess(self) -> None:
self.text_body: str = self._html_to_text(self.html_body)
self.message = MIMEMultipart()
self.message["Subject"] = self.subject
self.message["From"] = self._sender
self.message["To"] = ", ".join(self.recipient)
body = MIMEText(self.text_body, "plain")
self.message.attach(body)
with open(self.filename, "rb") as attatchment:
part = MIMEApplication(attatchment.read())
part.add_header("Content-Disposition", "attatchment", filename=self.filename.split("/")[-1])
self.message.attach(part)
self.sender = formataddr((self.sender_name, self._sender))
def send_mail(self) -> Response:
self._preprocess()
client = boto3.client('ses', region_name=self._aws_region)
response = client.send_raw_email(
Destinations=self.recipient,
RawMessage={"Data": self.message.as_string()},
Source=self.sender,
)
return Response.success('success', response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment