import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from jinja2 import Environment, FileSystemLoader
import os
# Email configuration
sender_email = "your_email@example.com"
receiver_email = "recipient_email@example.com"
password = "your_password"
subject = "Subject of the email"
# Jinja2 template configuration
template_dir = "templates"
template_file = "email_template.html"
attachment_path = "path/to/attachment.pdf"
# Load Jinja2 template
env = Environment(loader=FileSystemLoader(template_dir))
template = env.get_template(template_file)
template_vars = {"var1": "value1", "var2": "value2"} # Add any variables needed in your template
# Render Jinja2 template
html_content = template.render(template_vars)
# Create email message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# Attach HTML content
msg.attach(MIMEText(html_content, 'html'))
# Attach file
filename = os.path.basename(attachment_path)
attachment = open(attachment_path, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
# Send email
with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
Comments
Post a Comment