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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)