Solution to the garbled problem of sending mails based on Python _php tips

Source: Internet
Author: User
Tags python script in python

The company project needs to send the mail through the background, the message content includes the picture attachment. If sent through Phpmailer, because the mail server may have latency, send mail through Phpmailer, you need to wait for the message to send a successful return to the results, which in practice, it is proved that sometimes send messages can not immediately return results, affect the user experience.

So I sent a message through Python, and PHP invoked it by calling the script so that it returned immediately after the execution of the script, without having to determine if the message was sent successfully. Returns the success flag to the client whenever the script file is successfully executed. This greatly improves the mail delivery speed and ensures a good user experience effect.

However, in the message sent through Python, but encountered a garbled problem. During debugging, the following behavior occurs:

1, Chinese and English letters in combination with garbled.

2, reply the mail person's name two Chinese characters are normal, but three Chinese characters are garbled. This problem is hidden strong, I found this problem today, harm in front of the boss two times make the same mistake. Because I test ok AH (my name is two words), is not test three words of the situation, also did not expect the problem will be here.

3, the message subject garbled

4, everything is normal, but click on the message "reply", the content is part of garbled.

5, the content of the problem solved, found that the name of the reply is garbled. and QQ mailbox Normal, Foxmail Normal, 163 normal, Gmail Normal, but Outlook garbled.

Invoke Environment:

1, I will reply in PHP, reply to the mailbox, send a mailbox, filename, etc. as the parameters of the script, invoke the convenient execution of cmd command. As a parameter, some characters are special characters. such as &, single quotes, double quotes, and so on. Another problem is that there should be no spaces between each parameter. If there are spaces, then the order of the parameters is scrambled.

In short, garbled problem has been unable to solve perfectly. Finally no way, using the following way, finally solve the garbled problem.

In PHP will send the content of the message, such as the theme, reply name, mailbox, content, etc., to write to the configuration file, the profile name is random, the file directory is in the temporary directory of PHP. Ensure the use of multiple people. It then passes the configuration file name (including the path) when invoking the Python script in PHP, which is handled by reading the profile in Python. In this case, the theme and reply person, that is, involves the Chinese character part in 163 is garbled (the current content part has not measured, has identified the topic and the reply person involves the Chinese character in 163 mailbox to appear garbled, but in QQ mailbox does not have garbled, all is normal), the solution is through header ("XXXX" Utf-8 ") way to UTF8 after normal.

Share the relevant code below:

PHP invokes the Python script

Copy Code code as follows:

Generate INI configuration file
$sampleData = Array (
' Mail ' => array (
' Subject ' => ' Hello, pro, your friend sent you the Mail-xxx limited forwarding ',
' 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 Send mail script
Copy Code code 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", "to")
File_name=config.get ("Mail", "file_name")
from = "%s<xxxxx@xxx.com>"% Header ("XX Technology", "Utf-8")
Server = Smtplib. SMTP ("smtp.exmail.qq.com", 25)
Server.login ("Xxxx_business@5186.me", "itop202") #仅smtp服务器需要验证时

# construct Mimemultipart object as root container
main_msg = email. Mimemultipart.mimemultipart ()
# Constructs a Mimetext object to display content and attach to the root container
text_msg = email. Mimetext.mimetext ("xxx to help you forward the mail", _charset= "Utf-8")
Main_msg.attach (TEXT_MSG)
# constructs the Mimebase object as the file attachment content and attaches to the root container
ctype,encoding = Mimetypes.guess_type (file_name)
If CType is none or encoding are not none:
Ctype= ' Application/octet-stream '
Maintype,subtype = Ctype.split ('/', 1)
File_msg=email. Mimeimage.mimeimage (Open (file_name, ' RB '). Read (), subtype)
# # Set Attachment header
basename = Os.path.basename (file_name)
File_msg.add_header (' content-disposition ', ' attachment ', filename = basename) #修改邮件头
Main_msg.attach (FILE_MSG)
# Set Root Container properties
main_msg[' from '
If replytomail!= ' None ':
main_msg[' reply-to ' = "%s<%s>"% (Header (replytoname, "Utf-8"), Replytomail)
#main_msg [' to '] = to
main_msg[' Subject '] = Subject
main_msg[' Date ' = email. Utils.formatdate ()
#main_msg [' Bcc '] = to
# Get the full text formatted
Fulltext = Main_msg.as_string ()
# Send mail with SMTP
Try
Server.sendmail (from, To.split (';'), Fulltext)
Finally
Server.quit ()
Os.remove (file_name)


Send Plain text
Copy Code code as follows:

text_msg = email. Mimetext.mimetext ("XXXX to help you forward the mail", _charset= "Utf-8")
Main_msg.attach (TEXT_MSG)

Or
Copy Code code as follows:

Content=config.get ("Mail", "content")
Content=header (Content, "Utf-8") #如果加上这一句, the message could not be sent out. In fact, the following sentence has been encoded to deal with the content. This sentence will not be.
text_msg = email. Mimetext.mimetext (content,_charset= "Utf-8")
Main_msg.attach (TEXT_MSG)

Therefore, for the topic, the reply person involves the Chinese character, must use header ("xxxx", "Utf-8") the way carries on the encoding conversion. As for content, do not use header ("xxxx", "utf-8") repeated conversion, or there will be errors.

Related Article

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.