Skip to content

Instantly share code, notes, and snippets.

@ripiuk
Last active March 4, 2023 02:46
Show Gist options
  • Save ripiuk/2defb27fa633a6deb1bd328d20cc4479 to your computer and use it in GitHub Desktop.
Save ripiuk/2defb27fa633a6deb1bd328d20cc4479 to your computer and use it in GitHub Desktop.
Send HTML table as gmail body in Python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SENDER_EMAIL = 'some_email@gmail.com'
SENDER_PASSWORD = 'some_password'
SERVER = 'smtp.gmail.com:587'
RECEIVER_EMAIL = 'receiver_email@gmail.com'
SUBJECT = 'BLA-bla'
HTML = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
table {
background: white;
border-radius:3px;
border-collapse: collapse;
height: auto;
max-width: 900px;
padding:5px;
width: 100%;
animation: float 5s infinite;
}
th {
color:#D5DDE5;;
background:#1b1e24;
border-bottom: 4px solid #9ea7af;
font-size:14px;
font-weight: 300;
padding:10px;
text-align:center;
vertical-align:middle;
}
tr {
border-top: 1px solid #C1C3D1;
border-bottom: 1px solid #C1C3D1;
border-left: 1px solid #C1C3D1;
color:#666B85;
font-size:16px;
font-weight:normal;
}
tr:hover td {
background:#4E5066;
color:#FFFFFF;
border-top: 1px solid #22262e;
}
td {
background:#FFFFFF;
padding:10px;
text-align:left;
vertical-align:middle;
font-weight:300;
font-size:13px;
border-right: 1px solid #C1C3D1;
}
</style>
</head>
<body>
Dear Somebody,<br> <br>
Bla-bla-bla<br><br>
<table>
<thead>
<tr style="border: 1px solid #1b1e24;">
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
<th>head5</th>
<th>head6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
<br>
Bla-bla.<br>
For more assistance please contact our support team:
<a href='mailto:some_email@gmail.com'>some_email@gmail.com</a>.<br> <br>
Thank you!
</body>
</html>
"""
def _generate_message() -> MIMEMultipart:
message = MIMEMultipart("alternative", None, [MIMEText(HTML, 'html')])
message['Subject'] = SUBJECT
message['From'] = SENDER_EMAIL
message['To'] = RECEIVER_EMAIL
return message
def send_message():
message = _generate_message()
server = smtplib.SMTP(SERVER)
server.ehlo()
server.starttls()
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, message.as_string())
server.quit()
if __name__ == '__main__':
send_message()
@hadi131417
Copy link

Hello, Please help me to use data from data frame inside the table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment