Send html email with python
Question: I tried to send a email with html text using python.

The html text is loaded from a html file:

    
    
    ft = open("a.html", "r", encoding = "utf-8")
    text = ft.read()
    ft.close()
    

And after, I send the email:

    
    
    message = "From: %s\r\nTo: %s\r\nMIME-Version: 1.0\nContent-type: text/html\r\nSubject:
     %s\r\n\r\n%s" \
                 % (sender,receiver,subject,text)
       try:
          smtpObj = smtplib.SMTP('smtp.gmail.com:587')
          smtpObj.starttls()
          smtpObj.login(username,password)
          smtpObj.sendmail(sender, [receiver], message)
          print("\nSuccessfully sent email")
       except SMTPException:
          print("\nError unable to send email")
    

I got this error:

    
    
    Traceback (most recent call last):
      File "C:\Users\Henry\Desktop\email_prj\sendEmail.py", line 54, in <module>
        smtpObj.sendmail(sender, [receiver] + ccn, message)
      File "C:\Python33\lib\smtplib.py", line 745, in sendmail
        msg = _fix_eols(msg).encode('ascii')
      UnicodeEncodeError: 'ascii' codec can't encode character '\xe0' in position 1554:
      ordinal not in range(128)
    
      During handling of the above exception, another exception occurred:
    
      Traceback (most recent call last):
        File "C:\Users\Henry\Desktop\email_prj\sendEmail.py", line 56, in <module>
        except SMTPException:
      NameError: name 'SMTPException' is not defined
    

How can I solve this problem? Thanks.


Answer: > NameError: name 'SMTPException' is not defined

This is because in your current context, SMTPException doesn't stand for
anything.

You'll need to do:

    
    
    except smtplib.SMTPException:
    

* * *

Also, note that building the headers by hand is a bad idea. Can't you use
inbuilt modules?

The below is a copy-paste of _relevant parts_ from one of my projects.

    
    
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    
    ....
    ....
    ....
    msg = MIMEMultipart()
    
    msg['From'] = self.username
    msg['To'] = to
    msg['Subject'] = subject
    
    msg.attach(MIMEText(text))
    
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(self.username, self.password)
    mailServer.sendmail(self.username, to, msg.as_string())
    

