forked from Aniketc068/MX-Signer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_utils.py
More file actions
61 lines (50 loc) · 2.22 KB
/
email_utils.py
File metadata and controls
61 lines (50 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from env import EMAILTLS, EMAILHOST, EMAILPORT, EMAILHOST_USER, EMAILHOST_PASSWORD
EMAIL_USE_TLS = EMAILTLS
EMAIL_HOST = EMAILHOST
EMAIL_PORT = EMAILPORT
EMAIL_HOST_USER = EMAILHOST_USER
EMAIL_HOST_PASSWORD = EMAILHOST_PASSWORD
def send_email(subject, to_email, recipient_name, attachment_path=None):
try:
# Create the email message
msg = MIMEMultipart()
msg['From'] = EMAIL_HOST_USER
msg['To'] = to_email
msg['Subject'] = subject
# Read HTML content from the email.html file
email_html_path = 'templates/email.html' # Ensure this file exists in your project directory
if os.path.exists(email_html_path):
with open(email_html_path, 'r') as f:
email_body = f.read()
else:
raise FileNotFoundError(f"{email_html_path} not found.")
# Replace the placeholder [Recipient's Name] with recipient_name
email_body = email_body.replace('[Recipient\'s Name]', recipient_name)
# Attach the HTML body to the email
msg.attach(MIMEText(email_body, 'html'))
# Attach the signed PDF file if provided
if attachment_path:
part = MIMEBase('application', 'octet-stream')
with open(attachment_path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={os.path.basename(attachment_path)}')
msg.attach(part)
# Connect to the SMTP server and send the email
server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
server.starttls() # Start TLS encryption
server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
server.sendmail(EMAIL_HOST_USER, to_email, msg.as_string())
server.quit()
logging.info(f"Email sent successfully to {to_email}")
# print(f"Email sent successfully to {to_email}")
except Exception as e:
logging.error(f"Failed to send email: {str(e)}")
# print(f"Failed to send email: {str(e)}")