HTML email with image to send with python

environment

function

1. Settings and coding 1

gmail app settings

After logging in to google, move to Next URL

The screen will change to the image below, so turn on the 2-step authentication process and turn it on. Create an app password. Make a note of the app password somewhere.

image (9).png

2. Settings and coding 2

import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from email.mime.image import MIMEImage


class Mail:
    def __init__(self):
        setting_ini_dict = read_text_ini('setting_mail.ini')
        mail_dict = setting_ini_dict['mail']
        self.mail_address = mail_dict['address']
        self.mail_type = mail_dict['type']
        self.mail_password = mail_dict['password']
        self.api_url = '{The URL you want to run when you press the button}'

    def send_mail(self, to_addr, msg):
        smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
        smtpobj.ehlo()
        smtpobj.starttls()
        smtpobj.ehlo()
        smtpobj.login(self.mail_address, self.mail_password)
        smtpobj.sendmail(self.mail_address, to_addr, msg.as_string())
        smtpobj.close()

    def create_mail(self, to_address, subject, body_msg, uuid):
        api_url = self.api_url + f'?auth_key={uuid}'
        body_msg = body_msg.replace('@mail_api@', api_url)
        msg = MIMEMultipart('alternative')
        msg.attach(MIMEText(body_msg, 'html'))
        with open('qiita_logo.png', 'rb') as img:
            logo_img = MIMEImage(img.read())
            logo_img.add_header('Content-ID', '<logo_image>')

        with open('mail_icon.png', 'rb') as img:
            mail_img = MIMEImage(img.read())
            mail_img.add_header('Content-ID', '<mail_image>')
        msg.attach(logo_img)
        msg.attach(mail_img)

        msg['Subject'] = subject
        msg['From'] = self.mail_address
        msg['To'] = to_address
        msg['Date'] = formatdate()
        return msg

def read_text(file_path):
    s = ""
    with open(file_path, encoding="utf-8") as f:
        s = f.read()
        # print(s)
    return s

def read_text_ini(file_path):
    """
Reading from ini file
    Args:
        file_path:Path to file+file name

    Returns:
        ini_dic:Lexicographic string in ini file
    """
    import configparser
    ini_dict = configparser.ConfigParser()
    ini_dict.read(file_path, 'UTF-8')
    return ini_dict


mail = Mail()
to_address = '{Email address you want to send}'
subject = 'Email title'
body_msg = read_text('mail_format.html')
uuid = 'testetesfsdf'
msg = mail.create_mail(to_address, subject, body_msg, uuid)
mail.send_mail(to_address, msg)


mail_format.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Email authentication screen</title>
</head>
<body>
<img style="width: 100px;"
     src="cid:logo_image">
<div style="background-color: #d9d9d9; width: 80%; margin: 2% 5% 10% 0; padding: 30px;">
    <p style="text-align: center;"><img style="width: 50px;" src="cid:mail_image"></p>
    <h2 style="padding-left: 4%">Please check your email address</h2>
    <hr style="border:0; border-top:dashed; width: 96%;">
    <p style="padding-left: 4%">Please click this button to confirm your email address.<br>thank you for your cooperation.</p>
    <p style="text-align: center">
        <a style="position: relative;
  display: inline-block;
  padding: 0.25em 0.5em;
  text-decoration: none;
  color: #FFF;
  background: #03A9F4;/*color*/
  border: solid 1px #0f9ada;/*Line color*/
  border-radius: 4px;
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.2);
  text-shadow: 0 1px 0 rgba(0,0,0,0.2);" href="@mail_api@">Check your email</a>
    </p>
    <hr style="border:0; border-top:dashed; width: 96%;">
    <p style="padding-left: 4%">If you have any questions, please contact support.</p>
</div>
<div style="text-align: center">
    <p>You cannot reply to this email.<br>
        qiita.com Ltd. Qiita <br>
        <a href="https://qiita.com">qiita.com</a> <br>
        <a href="#">privacy policy</a>
    </p>

</div>

</body>
</html>

setting_mail.ini

# setting_mail.ini

[mail]
type = gmail
address = {The gmail address you set earlier}
password = {The password you saved earlier}

qiita_logo.png

qiita-logo.png

mail_icon.png mail_icon.png

Email sent

qiita_mail.png

Summary

I was able to send an html email using python and gmail. Sending with base64 by putting a local image in html and sending it, etc. Nowadays, there are some descriptions about methods that cannot be executed, so I summarized them briefly!

Recommended Posts

HTML email with image to send with python
Send email with Python
Send Japanese email with Python3
Send an email to Spushi's address with python
[Automation] Send Outlook email with Python
[Python] Send an email with outlook
Send image with python, save with php
Send email via gmail with Python 3.4.3.
[Python] Send email
[Python] Send email
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Send email to multiple recipients in Python (Python 3)
Send an email with Amazon SES + Python
Sample to convert image to Wavelet with Python
Send email with Django
Image processing with Python
Validate E-Mail with Python
Send a message to LINE with Python (LINE Notify)
Convert PDF to image (JPEG / PNG) with Python
How to crop an image with Python + OpenCV
Sample to send slack notification with python lambda
Send an email with Excel attached in Python
Post an article with an image to WordPress with Python
What to do if you couldn't send an email to Yahoo with Python.
Send an email to a specific email address with python without SMTP settings
Image processing with Python (Part 2)
Connect to BigQuery with Python
How to scrape image data from flickr with python
Image editing with python OpenCV
Connect to Wikipedia with Python
Post to slack with Python 3
Sorting image files with Python (2)
Sorting image files with Python (3)
Convert the image in .zip to PDF with Python
Image processing with Python (Part 1)
Send email in Python (Outlook)
Tweet with image in Python
Sorting image files with Python
Image processing with Python (Part 3)
Switch python to 2.7 with alternatives
Write to csv with Python
To automatically send an email with an attachment using the Gmail API in Python
Send using Python with Gmail
[Python] Image processing with scikit-image
I tried to find the entropy of the image with python
[Python] Send gmail with python: Send one by one with multiple image files attached
How to install NPI + send a message to line with python
[Python] Send an email from gmail with two-step verification set
I tried various methods to send Japanese mail with Python
[Ev3dev] How to display bmp image on LCD with python
Send experiment results (text and images) to slack with Python
[Let's play with Python] Image processing to monochrome and dots
Send push notifications to iOS apps with Python2 (with sample code)
Convert .ipynb to .html (with BatchFile)
Cut out an image with python
Python: How to use async with
[Python] Using OpenCV with Python (Image Filtering)
Link to get started with python
[Python] Write to csv file with Python
[Python] Using OpenCV with Python (Image transformation)
Create folders from '01' to '12' with python