A small e-letter project was created using Jinja.

Source: Internet
Author: User
An HTML e-letter project was created.
Using jinja2 as the mail template, it is great to generate HTML mail content.
It took only two hours for the entire project to be developed, but debugging took about half a day. The generated emails were always unavailable.

Therefore, open the debuglevel of SMTP and find that the email has been sent to the queue, but the email cannot be received. mail Server is exchange. similar programs have been written in Java before, and there is no problem (HTML mail is also sent through SMTP protocol ). why is there a problem with this python implementation?

I have suspected Python SMTP module usage, Python SMTP HTML writing, and SMTP subject and content do not support Unicode.
Finally, the culprit was found: as long as the subject of the email contains the 13 characters "Please check.", the mail will sink into the sea. Is there a rule for Exchange server?

#------------------
MATERIALS:
#------------------
The cnblogs article is good. <main methods for sending various emails using Python>,
Http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html

 


#------------------
Code structure
#------------------
The following is a brief description of the project structure. Based on my scaffolding project, a small amount of cropping is made and two directories are added, scripts and templates, the scripts directory stores the e-letter generation and sending scripts, and the templates directory stores the e-letter template.
Add mail_service.py and modify the code found on the Internet to send HTML emails.

 
Py_package
| -- Scripts
| -- Check1.py
| -- Check2.py
| -- Templates
| --Check1.html
| --Check2.html

#-*-Coding: UTF-8 -*-
# Check1.py
'''
Created on

'''

From _ future _ import absolute_import
Import jinja2
From jinja2.loaders import filesystemloader

Def get_template (file_name ):
'''
Get template HTML with jinja2 format in Templates folder
'''
Template_path = OS. Path. Join (OS. Path. dirname (OS. Path. dirname (_ file _), 'templates ')
Template_env = jinja2.environment (loader = filesystemloader (template_path ))
Return template_env.get_template (file_name)


Def check ():
Template+get_template('check1.html ')
Something = 'something here'
Mail_body = template. Render (something = something)
Mail_sender = htmlmailsender ()
Mail_subject = 'some subject here'
# Mail_subject = 'Please check. '# cannot send out, why?
Mail_to = ['[email protected]', 'B .corp.com']
Mail_cc = []
Mail_sender.send_html_mail (mail_to, mail_cc, mail_subject, mail_body)

 

 


#-*-Coding: UTF-8 -*-
# Conf. py
'''
Created on 2014-6-23

'''
From _ future _ import absolute_import
Import Logging

# Logging
Log_level = logging. Info

 
# Email setting
Smtp_host = "10.10.10.10"
Smtp_port = 25
Smtp_over_ssl = false
Mail_user = "[email protected]"
Mail_pwd = "" # If no auth required, set PWD as empty
 

 



#-*-Coding: UTF-8 -*-
# Mail_service.py
'''
Created on 2014-6-23

'''
From _ future _ import absolute_import
Import Logging
From. Import Conf


Class htmlmailsender (object ):
Logger = logging. getlogger (_ name __)

Def _ init _ (Self ):
# Read mail settings from configure file
Self. smtp_host = Conf. smtp_host
Self. smtp_port = Conf. smtp_port
Self. smtp_over_ssl = Conf. smtp_over_ssl
Self. mail_user = Conf. mail_user
Self. mail_pwd = Conf. mail_pwd



Def send_html_mail (self, to_list, cc_list, subject, body ):
Self.logger.info ('send _ html_mail () called .')

Import smtplib
From email. Mime. Text import mimetext
From email. Mime. multipart import mimemultipart

# Construct email
Msgroot = mimemultipart ('related ')
Msgroot ['subobject'] = subject
Msgroot ['from'] = self. mail_user
Msgroot ['to'] = ",". Join (to_list)
Msgroot ['cc'] = ",". Join (cc_list)
# Msgroot ['bcc '] = ",". Join (cc_list)
Msgroot. Preamble = 'this is a multi-part message in MIME format .'

# Encapsulate the plain and HTML versions of the message body in
# 'Alternative 'part, so message agents can decide which they want to display.
Msgalternative = mimemultipart ('alternative ')
Msgroot. Attach (msgalternative)

# Add plain content
Msgtext = mimetext ('this is HTML mail. If you see this message, which means you will not see the real mail content. ', 'plain ')
Msgalternative. Attach (msgtext)

# Add HTML content
Msgtext = mimetext (body, 'html ')
Msgalternative. Attach (msgtext)
 
Try:
If not self. smtp_over_ssl:
If self. smtp_port = '':
S = smtplib. SMTP (self. smtp_host)
Else:
S = smtplib. SMTP (self. smtp_host, self. smtp_port)
Else:
If self. smtp_port = '':
S = smtplib. smtp_ssl (self. smtp_host)
Else:
S = smtplib. smtp_ssl (self. smtp_host, self. smtp_port)

S. set_debuglevel (true) # print stmp actions to stdout
If self. mail_pwd:
S. login (self. mail_user, self. mail_pwd)

To_addrs = to_list + cc_list
S. Sendmail (self. mail_user, to_addrs, msgroot. as_string ())
# S. Sendmail (from_addr, to_addrs, 'test message ')
S. Quit ()

Self.logger.info ("" mail sent. Find details below,
To_list: % s
Cc_list: % s
Subject: % s
Body: % s "" % (to_list, cc_list, subject, body ))
Return true
Failed t exception, EX:
Self. Logger. Exception (Ex)
Return false

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.