Search code examples
pythonhtml-email

Use a variable inside HTML email?


I'm using information found on this post Sending Email Using Python

So far the instructions were perfect. I have two additional things I'd like to do:

  1. Call a variable inside the body
  2. Add an attachment

The variable would be todays date. This is it:

today = datetime.datetime.today ()
tday = today.strftime ("%m-%d-%Y")

I know that with mailx, you can attach with the -a option.


Solution

  • To call the variables inside the html body ,just convert them to string to concatenate them in the body

    from datetime import datetime
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    today = datetime.today ()
    tday = today.strftime ("%m-%d-%Y")
    
    # email subject, from , to will be defined here
    msg = MIMEMultipart()
    
    html = """\
    <html>
      <head></head>
      <body>
        <p>Hi!<br>
           How are you?<br>
           """ +str(today)+ """ and """ +str(tday)+ """
        </p>
      </body>
    </html>
    """
    msg.attach(MIMEText(html, 'html'))
    

    For attachments please look at http://naelshiab.com/tutorial-send-email-python/

    EDIT : The link provided above seems not available, so the code snippet for sending attachments via email (specifically from gmail) is below

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
    
    msg = MIMEMultipart()
    
    msg['From'] = "from email address"
    msg['To'] = "to email address" 
    msg['Subject'] = "Subject line" 
    body = """Body 
              content"""
    
    msg.attach(MIMEText(body, 'plain'))
    attachment = open("/path/to/file", "rb") 
    p = MIMEBase('application', 'octet-stream') 
    
    # To change the payload into encoded form 
    p.set_payload((attachment).read()) 
    
    # encode into base64 
    encoders.encode_base64(p) 
    
    p.add_header('Content-Disposition', "attachment; filename= %s" % filename) 
    
    # attach the instance 'p' to instance 'msg' 
    msg.attach(p) 
    
    s = smtplib.SMTP('smtp.gmail.com', 587) 
    s.starttls() # for security
    s.login("from email address", "your password") 
    
    text = msg.as_string() 
    
    # sending the mail 
    s.sendmail("from email address", "to email address" , text)
    s.quit() 
    

    Note : Google will some times block logins from other application (less secure apps) so there is a need to allow this access in your Google account settings https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none