search
HomeBackend DevelopmentPHP Tutorial基于python发送邮件的乱码问题的解决办法_PHP

python

公司项目中需要通过后台发送邮件,邮件内容包括图片附件。如果通过PHPmailer发送,由于邮件服务器可能存在延迟现象,通过PHPmailer发送邮件,需要等待邮件发送成功后才能返回结果,这在实践中证明,有时发送邮件无法即时返回结果,影响用户体验。

于是我通过python发送邮件,PHP通过调用脚本方式来调用,这样执行脚本成功后立即返回,而无需判断邮件是否发送成功。只要成功执行脚本文件即向客户端返回成功标志。这样极大的提高了邮件发送速度,保证良好的用户体验效果。

但是,在通过python发送邮件,却遇到了乱码的问题。在调试过程中出现了以下现象:

1、中文与英文字母结合出现乱码。

2、回复邮件人的姓名两个汉字正常、但三个汉字就乱码。这个问题隐藏性强,我到今天才发现这个问题,害的在老板面前两次犯同样错误。因为我测试OK啊(我姓名两个字),就是没有测试三个字的情况,也没想到问题会出在这里。

3、邮件主题乱码

4、一切正常,但点击邮件“回复”时,出现的内容部分乱码。

5、内容问题解决后,发现回复的姓名也乱码。而且QQ邮箱正常、foxmail正常、163正常、gmail正常,但outlook乱码。

调用环境:

1、我在PHP中将回复人,回复邮箱,发送邮箱,文件名等做为脚本的参数,调用cmd命令的方便执行。而做为参数,有些字符是特殊字符。比如&符,单引号,双引号等问题。另外还有一个问题是每个参数间不能有空格。如果有空格,那么参数的顺序就打乱了。

总之,乱码问题一直无法完美解决。最后没有办法,采用下面方式,终于解决乱码问题。

在PHP中将发送邮件的内容,比如主题、回复姓名、邮箱、内容等等,写到配置文件中去,这个配置文件名是随机的,文件目录是在PHP的临时目录。确保多人使用的情况。然后在PHP中调用python脚本时传递配置文件名(含路径也可以),在python中通过读取该配置文件来处理。在这种情况下,主题和回复人,也就是涉及汉字部分在163中是乱码(目前内容部分没测,已经确定主题及回复人涉及汉字在163邮箱中出现乱码,但在QQ邮箱中没有乱码,一切正常),解决办法是通过Header("xxxx","utf-8")方式转为utf8后都正常。

下面分享一下相关代码:

PHP调用python脚本
复制代码 代码如下:
//生成ini配置文件
$sampleData = array(
  'mail' => array(
    'subject' =>'hello,亲,你朋友给你发送的邮件-xxx有限公司转发',
    '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发送邮件脚本
复制代码 代码如下:
# -*- 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" % (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")重复转换了,否则会出现错误。

Statement
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools