How to solve the garbled problem of sending emails based on python

Source: Internet
Author: User
This article introduces how to solve the garbled problem of sending emails based on python. If you need a friend, refer to the company's projects and send an email in the background. the email content includes Image attachments. If the email is sent through PHPmailer, because the email server may be delayed, you must wait until the email is sent successfully before returning the result, sometimes sending emails cannot return results in real time, affecting user experience.

So I sent an email through python, and PHP called it by calling a script. This way, after the script is successfully executed, it will be returned immediately without judging whether the email was successfully sent. If the script file is successfully executed, a success flag is returned to the client. This greatly improves the Mail sending speed and ensures a good user experience.

However, garbled characters occur when sending emails via python. The following occurs during debugging:

1. garbled characters appear in the combination of Chinese and English letters.

2. the email recipient's name and two Chinese characters are normal, but the three Chinese characters are garbled. This problem is highly concealed. I have discovered it today, and I have made the same mistake twice in front of my boss. Because I tested OK (my name is two characters), that is, I did not test three words, and I did not expect the problem to happen here.

3. garbled email subject

4. everything is normal, but when you click "reply" in the email, some garbled content appears.

5. after the content problem is resolved, the name of the reply is garbled. In addition, the QQ mailbox is normal, foxmail is normal, 163 is normal, and gmail is normal, but the outlook is garbled.

Call environment:

1. in PHP, I will reply to the user, reply to the mailbox, send the mailbox, and file name as the script parameters, and call the cmd command for convenient execution. As a parameter, some characters are special characters. Such as quotation marks, single quotes, and double quotation marks. Another problem is that each parameter cannot contain spaces. If there are spaces, the order of parameters is messy.

In short, the garbled problem has never been solved perfectly. Finally, there is no way to use the following method to finally solve the garbled problem.

In PHP, the content of the email, such as the subject, reply name, email address, and content, is written to the configuration file. the configuration file name is random, the file directory is a temporary directory in PHP. Ensure that multiple users are used. Then, when the python script is called in PHP, the configuration file name (including the path) is passed. in python, the configuration file is read for processing. In this case, the subject and the respondent, that is, the Chinese characters involved, are garbled in section 163. (currently, the content is not tested, it has been confirmed that the subject and the respondent involved Chinese characters contain garbled characters in the 163 mailbox, but there is no garbled code in the QQ mailbox, everything is normal). The solution is to use the Header ("xxxx", "UTF-8 ") after the method is converted to utf8, it is normal.

The following code is used:

PHP calls the python script

// Generate the ini configuration file $ sampleData = array ('mail' => array ('subobject' => 'Hello, dear, emails sent To you by your friend-xxx Company Limited Forward ',' replytoname' => $ send_name, 'replytomail' => $ send_email, 'To' => $ receive_email, 'File _ name' => realpath ($ target_path),); $ filename = getUnique (). '. ini '; write_ini_file ($ sampleData, 'd:/PHP/Php/tmp /'. $ filename, true); $ cmd = 'start mmail. PY '. $ filename; $ r = exec ($ cmd, $ out, $ status); if (! $ Status) echo 'OK' else echo 'fail'


Python email sending script

#-*-Coding: UTF-8-*-import smtplibimport email. MIMEMultipart # import MIMEMultipartimport email. MIMEText # import MIMETextimport email. MIMEBase # import MIMEBaseimport OS. pathimport sysfrom email. header import Headerimport mimetypesimport email. MIMEImage # import MIMEImageimport ConfigParserimport stringinifile = u 'd:/PHP/Php/tmp/'+ sys. argv [1] config = ConfigParser. configParser () config. read (inifile) OS. remove (inifile) subject = Header (config. get ("mail", "subject"), "UTF-8") ReplyToName = config. get ("mail", "ReplyToName") ReplyToMail = config. get ("mail", "ReplyToMail") To = config. get ("mail", "To") file_name = config. get ("mail", "file_name") From = "% s
 
  
"% Header (" xx technology "," UTF-8 ") server = smtplib. SMTP ("smtp.exmail.qq.com", 25) server. login ("xxxx_business@5186.me", "itop202") # only when the smtp server needs verification # construct the MIMEMultipart object as the root container main_msg = email. MIMEMultipart. MIMEMultipart () # construct the MIMEText object as the Mail display content and attach it to the root container text_msg = email. MIMEText. MIMEText ("xxx emails forwarded by You", _ charset = "UTF-8") main_msg.attach (text_msg) # constructs a MIMEBase object as an attachment to the file and attaches it to the ctype of the root container, encoding = mimetypes. guess_type (file_name) I F ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype. split ('/', 1) file_msg = email. MIMEImage. MIMEImage (open (file_name, 'RB '). read (), subtype) # set the attachment header basename = OS. path. basename (file_name) file_msg.add_header ('content-disposition', 'attachment ', filename = basename) # Modify the mail header main_msg.attach (file_msg) # set the root container attribute main_msg ['from'] = Fromif ReplyToMail! = 'None': main_msg ['reply-to '] = "% s <% s>" % (Header (ReplyToName, "UTF-8"), ReplyToMail) # main_msg ['to'] = Tomain_msg ['subobject'] = subjectmain_msg ['Date'] = email. utils. formatdate () # main_msg ['bcc '] = To # obtain the formatted full text fullText = main_msg.as_string () # use smtp To send an email try: server. sendmail (From,. split (';'), fullText) finally: server. quit () OS. remove (file_name)
 


Send plain text

Text_msg = email. MIMEText. MIMEText ("xxxx emails forwarded by You", _ charset = "UTF-8") main_msg.attach (text_msg)

Or

Content = config. get ("mail", "content") content = Header (content, "UTF-8") # if this sentence is added, the mail cannot be sent. In fact, the following sentence has encoded the content. This sentence is not required. Text_msg = email. MIMEText. MIMEText (content, _ charset = "UTF-8") main_msg.attach (text_msg)


Therefore, if the subject or the respondent involves Chinese characters, use the Header ("xxxx", "UTF-8") for encoding and conversion. As for the content, do not use the Header ("xxxx", "UTF-8") to repeat the conversion; otherwise, an error will occur.

The above is the solution to the garbled code issue sent based on python _ php tip content. For more information, please follow the PHP Chinese website (www.php1.cn )!

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.