Solution to python-based email garbled characters _ PHP Tutorial

Source: Internet
Author: User
A solution to the garbled problem of sending emails based on python. In a company project, you must send an email in the background. the email content includes Image attachments. If the email is sent via PHPmailer, due to the delay of the mail server, you must send the email via the background in the project sent by PHPmailer. 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

The code is as follows:

// Generate the ini configuration file
$ SampleData = array (
'Mail' => array (
'Subobject' => 'Hello, dear, the email your friend sent to you-xxx company forwarding ',
'Replace ame' => $ 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'
Echo 'fail'

Python email sending script

The code is as follows:

#-*-Coding: UTF-8 -*-
Import smtplib
Import email. MIMEMultipart # import MIMEMultipart
Import email. MIMEText # import MIMEText
Import email. MIMEBase # import MIMEBase
Import OS. path
Import sys
From email. header import Header
Import mimetypes
Import email. MIMEImage # import MIMEImage
Import ConfigParser
Import string

Inifile = 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", "")
File_name = config. get ("mail", "file_name ")
From = "% s "% Header (" xx technology "," UTF-8 ")
Server = smtplib. SMTP ("", 25)
Server. login ("", "itop202") # only when the smtp server needs verification

# Construct a MIMEMultipart object as the root container
Main_msg = email. MIMEMultipart. MIMEMultipart ()
# Construct a MIMEText object as the Mail display content and attach it to the root container
Text_msg = email. MIMEText. MIMEText ("email forwarded by xxx", _ charset = "UTF-8 ")
Main_msg.attach (text_msg)
# Construct a MIMEBase object as an attachment to the file and attach it to the root container
Ctype, encoding = mimetypes. guess_type (file_name)
If 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)
# Setting root container properties
Main_msg ['from'] = From
If ReplyToMail! = 'None ':
Main_msg ['reply-to'] = "% s <% s>" % (Header (ReplyToName, "UTF-8"), ReplyToMail)
# Main_msg ['to'] =
Main_msg ['subobject'] = Subject
Main_msg ['Date'] = email. Utils. formatdate ()
# Main_msg ['bcc '] =
# Obtain the formatted complete text
FullText = main_msg.as_string ()
# Sending emails using smtp
Server. sendmail (From, To. split (';'), fullText)
Server. quit ()
OS. remove (file_name)

Send plain text

The code is as follows:

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


The code is as follows:

Content = config. get ("mail", "content ")
Content = Header (content, "UTF-8") # if this sentence is added, the email 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.

Bytes. If you send messages via PHPmailer, because the mail server may be delayed, you can send emails via PHPmailer...

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: 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.