Home > Backend Development > PHP Tutorial > Solution to the garbled problem of sending emails based on python_PHP tutorial

Solution to the garbled problem of sending emails based on python_PHP tutorial

WBOY
Release: 2016-07-21 15:11:53
Original
991 people have browsed it

In company projects, emails need to be sent through the background, and the email content includes image attachments. If sent through PHPmailer, due to possible delays in the mail server, sending emails through PHPmailer requires waiting for the email to be sent successfully before the results can be returned. This has been proven in practice that sometimes sending emails cannot return results immediately, affecting the user experience.

So I sent the email through python, and PHP called it by calling the script, so that it would return immediately after successfully executing the script without having to judge whether the email was sent successfully. As long as the script file is successfully executed, a success flag is returned to the client. This greatly improves the email sending speed and ensures a good user experience.

However, when sending emails through python, I encountered the problem of garbled characters. The following phenomenon occurred during the debugging process:

1. The combination of Chinese and English letters causes garbled characters.

2. Two Chinese characters for the name of the person who replied to the email are normal, but three Chinese characters are garbled. This problem is very hidden. I only discovered this problem today, which caused me to make the same mistake twice in front of my boss. Because my test was OK (my name is two characters), but I didn’t test three characters, and I didn’t expect that the problem would arise here.

3. The email subject is garbled

4. Everything is normal, but when you click "Reply" on the email, some of the content that appears is garbled.

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

Calling environment:

1. I use the reply person, reply email, sending email, file name, etc. as parameters of the script in PHP, and call the cmd command for convenient execution. As parameters, some characters are special characters. For example, issues such as ampersand, single quotation marks, double quotation marks, etc. Another problem is that there cannot be spaces between each parameter. If there are spaces, the order of parameters is disrupted.

In short, the problem of garbled characters cannot be perfectly solved. In the end, there was no other way, so I adopted the following method to finally solve the garbled code problem.

In PHP, write the content of the sent email, such as subject, reply name, email, content, etc., into the configuration file. The name of this configuration file is random, and the file directory is in the temporary directory of PHP. Ensure multi-person use. Then pass the configuration file name (including the path) when calling the python script in PHP, and process it by reading the configuration file in python. In this case, the topic and reply person, that is, the part involving Chinese characters, are garbled in 163 (the content part has not been tested at present. It has been determined that the topic and reply person involving Chinese characters are garbled in the 163 mailbox, but there are no garbled characters in the QQ mailbox , everything is normal), the solution is to convert it to utf8 through Header("xxxx", "utf-8") and everything is normal.

Share the relevant code below:

PHP calls python script

Copy code The code is as follows:

//Generate ini configuration file
$sampleData = array(
'mail' => array(
'subject' =>'Hello, dear, your friend sent you an email - forwarded by xxx Co., Ltd.',
'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 email script
Copy code 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","To")
file_name=config.get("mail","file_name")
From = "%s" % Header("xx科技","utf-8")
server = smtplib.SMTP("smtp.exmail.qq.com",25)
server.login("xxxx_business@5186.me","itop202") #仅smtp服务器需要验证时

# 构造MIMEMultipart对象做为根容器
main_msg = email.MIMEMultipart.MIMEMultipart()
# 构造MIMEText对象做为邮件显示内容并附加到根容器
text_msg = email.MIMEText.MIMEText("xxx帮你转发的邮件",_charset="utf-8")
main_msg.attach(text_msg)
# 构造MIMEBase对象做为文件附件内容并附加到根容器
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)
## 设置附件头
basename = os.path.basename(file_name)
file_msg.add_header('Content-Disposition','attachment', filename = basename)#修改邮件头
main_msg.attach(file_msg)
# 设置根容器属性
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
# 得到格式化后的完整文本
fullText = main_msg.as_string()
# 用smtp发送邮件
try:
    server.sendmail(From, To.split(';'), fullText)
finally:
    server.quit()
    os.remove(file_name)


发送纯文本
复制代码 代码如下:

text_msg = email.MIMEText.MIMEText("xxxx帮你转发的邮件",_charset="utf-8")
main_msg.attach(text_msg)

或者
复制代码 代码如下:

content=config.get("mail","content")
content=Header(content,"utf-8")#如果加上这一句,邮件发不出去。其实下面这句已经对内容进行了编码处理。这一句就不要了。
text_msg = email.MIMEText.MIMEText(content,_charset="utf-8")
main_msg.attach(text_msg)

因此,对于主题、回复人涉及汉字的,要用Header("xxxx","utf-8")方式进行编码转换。至于内容,就不要用Header("xxxx","utf-8")重复转换了,否则会出现错误。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/326788.htmlTechArticle公司项目中需要通过后台发送邮件,邮件内容包括图片附件。如果通过PHPmailer发送,由于邮件服务器可能存在延迟现象,通过PHPmailer发送邮...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template