A solution to the problem of scrambled messages based on python

  • 2020-05-30 19:45:35
  • OfStack

The company needs to send emails through the background in the project, including picture attachment. If it is sent via PHPmailer, the mail server may have a delay. If it is sent via PHPmailer, it needs to wait for the mail to be sent successfully before it can return the result. This has been proved in practice that sometimes the mail cannot return the result immediately, which will affect the user experience.

So I send the message via python, and PHP calls it by calling the script, so that it returns immediately after the successful execution of the script, without having to judge whether the message was sent or not. Returns a success flag to the client upon successful execution of the script file. This greatly improves the speed of mail delivery and ensures a good user experience.

However, when sending emails via python, I encountered the problem of garbled codes. During the debugging process, the following phenomena occurred:

1, the combination of Chinese and English letters appear garbled code.

2. The name of the person who replied to the email is in two normal Chinese characters, but three Chinese characters are scrambled. This problem is so hidden that I didn't find it until today. I made the same mistake twice in front of my boss. Because I tested OK (my name is two words), even if I didn't test three words, I didn't expect the problem would be here.

3. The subject line is garbled

4. The first cut is normal, but when you click "reply" in the email, some garbled codes appear.

5. After solving the content problem, I found that the name of the reply was also garbled. Moreover, QQ mailbox is normal, foxmail mailbox is normal, 163 mailbox is normal, gmail mailbox is normal, but outlook mailbox is scrambled.

Calling environment:

1. In PHP, I take the responder, reply mailbox, sending mailbox and file name as the parameters of the script, and call cmd command for easy execution. As arguments, some characters are special characters. Such as & Character, single quotation mark, double quotation mark and so on. Another problem is that you can't have Spaces between each parameter. If there are Spaces, the order of the arguments is out of order.

In short, garbled code problem 1 can not be solved perfectly. Finally, there is no way to use the following way, finally solve the problem of garbled code.

In PHP, the content of the message, such as subject, reply name, mailbox, content, etc., will be written to the configuration file. This configuration file name is random, and the file directory is in the temporary directory of PHP. Make sure you have multiple users. You then pass the configuration name (including the path) when the python script is called from PHP, which is handled by reading the configuration file from python. In this case, the topic and responder, that is, the part involving Chinese characters, are gargoyles in 163 (currently not tested in the content part, it has been determined that the topic and responder involved Chinese characters are gargoyles in 163 mailbox, but there is no gargoyles in QQ mailbox, and the 1 cut is normal). The solution is to turn them into utf8 by means of Header("xxxx"," utf-8 ").

Share 1 related code below:

PHP calls the python script


// generate ini The configuration file 
$sampleData = array(
  'mail' => array(
    'subject' =>'hello, Dear, your friend sent you an email - xxx Forwarding by limited company ',
    '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 sends the mail script

# -*- 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 Science and technology ","utf-8")
server = smtplib.SMTP("smtp.exmail.qq.com",25)
server.login("xxxx_business@5186.me","itop202") # only smtp When the server needs validation 
#  structure MIMEMultipart Object as the root container 
main_msg = email.MIMEMultipart.MIMEMultipart()
#  structure MIMEText Object is displayed as the message content and attached to the root container 
text_msg = email.MIMEText.MIMEText("xxx The email you forwarded ",_charset="utf-8")
main_msg.attach(text_msg)
#  structure MIMEBase Object as file attachment content and attached 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 attachment header 
basename = os.path.basename(file_name)
file_msg.add_header('Content-Disposition','attachment', filename = basename)# Modify message headers 
main_msg.attach(file_msg)
#  Set the root container property 
main_msg['From'] = 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 formatted full text 
fullText = main_msg.as_string()
#  with smtp Send E-mail 
try:
    server.sendmail(From, To.split(';'), fullText)
finally:
    server.quit()
    os.remove(file_name)

Send plain text

text_msg = email.MIMEText.MIMEText("xxxx The email you forwarded ",_charset="utf-8")
main_msg.attach(text_msg)

or

content=config.get("mail","content")
content=Header(content,"utf-8")# If I add this 1 The email can't go out. In fact, the following sentence has already encoded the content. this 1 No more sentences. 
text_msg = email.MIMEText.MIMEText(content,_charset="utf-8")
main_msg.attach(text_msg)

Therefore, if the subject and the respondent are related to Chinese characters, Header("xxxx"," utf-8 ") shall be used for encoding conversion. As for the content, don't repeat the conversion with Header("xxxx"," utf-8 "), or you'll get an error.


Related articles: