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

Jul 21, 2016 pm 03:11 PM
python Garbled characters company Method send Backstage based on of solve pass mail need

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发送邮...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles