php发邮件foxmail标题显示乱码问题解决方案

简介: 之前在大神那里找了一个SMTP发送邮件的源码,应用之后是可以发送邮件了,然后web查看邮件也正常,但是foxmail客户端一直显示标题乱码,正文是正常的,几经搜索之后,终于发现原来邮件是base64编码的,所有需要将标题经过编码之后才发送,测试之后,果然正常了。

之前在大神那里找了一个SMTP发送邮件的源码,应用之后是可以发送邮件了,然后web查看邮件也正常,但是foxmail客户端一直显示标题乱码,正文是正常的,几经搜索之后,终于发现原来邮件是base64编码的,所有需要将标题经过编码之后才发送,测试之后,果然正常了。

$mailsubject = "=?UTF-8?B?".base64_encode($mailsubject)."?=";    //标题转码,防止foxmail客户端乱码

详细代码如下,mail.php是借用大神的,但是忘记在哪下载了的,如需要下线,请联系。

mail.php

<?php
class smtp
{
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
var $sock;
function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
{
	$this->debug = true;
	$this->smtp_port = $smtp_port;
	$this->relay_host = $relay_host;
	$this->time_out = 30;
	$this->auth = $auth;
	$this->user = $user;
	$this->pass = $pass;
	
	$this->host_name = "localhost";
	$this->log_file ="";
	$this->sock = FALSE;
}
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
{
	$mail_from = $this->get_address($this->strip_comment($from));
	$body = ereg_replace("(^|(\r\n))(\\.)", "\\1.\\3", $body);
	$header .= "MIME-Version:1.0\r\n";
	if($mailtype=="HTML")
	{
	$header .= "Content-Type:text/html\r\n";
	}
	$header .= "To: ".$to."\r\n";
	if ($cc != "")
	{
	$header .= "Cc: ".$cc."\r\n";
	}
	$header .= "From: $from<".$from.">\r\n";
	$header .= "Subject: ".$subject."\r\n";
	$header .= $additional_headers;
	$header .= "Date: ".date("r")."\r\n";
	$header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n";
	list($msec, $sec) = explode(" ", microtime());
	$header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";
	$TO = explode(",", $this->strip_comment($to));
	
	if ($cc != "") {
	$TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
	}
	if ($bcc != "") {
	$TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
	}
	
	$sent = TRUE;
	foreach ($TO as $rcpt_to) {
	$rcpt_to = $this->get_address($rcpt_to);
	if (!$this->smtp_sockopen($rcpt_to)) {
	$this->log_write("Error: Cannot send email to ".$rcpt_to."\n");
	$sent = FALSE;
	continue;
	}
	if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
	$this->log_write("E-mail has been sent to <".$rcpt_to.">\n");
	} else {
	$this->log_write("Error: Cannot send email to <".$rcpt_to.">\n");
	$sent = FALSE;
	}
	fclose($this->sock);
	$this->log_write("Disconnected from remote host\n");
	}
	echo "<br>";
	echo $header;
	return $sent;
}
  
/* Private Functions */
  
function smtp_send($helo, $from, $to, $header, $body = "")
{
if (!$this->smtp_putcmd("HELO", $helo)) {
return $this->smtp_error("sending HELO command");
}
#auth
if($this->auth){
if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
return $this->smtp_error("sending HELO command");
}
  
if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
return $this->smtp_error("sending HELO command");
}
}
#
if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
return $this->smtp_error("sending MAIL FROM command");
}
  
if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
return $this->smtp_error("sending RCPT TO command");
}
  
if (!$this->smtp_putcmd("DATA")) {
return $this->smtp_error("sending DATA command");
}
  
if (!$this->smtp_message($header, $body)) {
return $this->smtp_error("sending message");
}
  
if (!$this->smtp_eom()) {
return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
}
  
if (!$this->smtp_putcmd("QUIT")) {
return $this->smtp_error("sending QUIT command");
}
  
return TRUE;
}
  
function smtp_sockopen($address)
{
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx($address);
} else {
return $this->smtp_sockopen_relay();
}
}
  
function smtp_sockopen_relay()
{
$this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."\n");
$this->log_write("Error: ".$errstr." (".$errno.")\n");
return FALSE;
}
$this->log_write("Connected to relay host ".$this->relay_host."\n");
return TRUE;;
}
  
function smtp_sockopen_mx($address)
{
$domain = ereg_replace("^.+@([^@]+)$", "\\1", $address);
if (!@getmxrr($domain, $MXHOSTS)) {
$this->log_write("Error: Cannot resolve MX \"".$domain."\"\n");
return FALSE;
}
foreach ($MXHOSTS as $host) {
$this->log_write("Trying to ".$host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Warning: Cannot connect to mx host ".$host."\n");
$this->log_write("Error: ".$errstr." (".$errno.")\n");
continue;
}
$this->log_write("Connected to mx host ".$host."\n");
return TRUE;
}
$this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n");
return FALSE;
}
  
function smtp_message($header, $body)
{
fputs($this->sock, $header."\r\n".$body);
$this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> "));
  
return TRUE;
}
  
function smtp_eom()
{
fputs($this->sock, "\r\n.\r\n");
$this->smtp_debug(". [EOM]\n");
  
return $this->smtp_ok();
}
  
function smtp_ok()
{
$response = str_replace("\r\n", "", fgets($this->sock, 512));
$this->smtp_debug($response."\n");
  
if (!ereg("^[23]", $response)) {
fputs($this->sock, "QUIT\r\n");
fgets($this->sock, 512);
$this->log_write("Error: Remote host returned \"".$response."\"\n");
return FALSE;
}
return TRUE;
}
  
function smtp_putcmd($cmd, $arg = "")
{
if ($arg != "") {
if($cmd=="") $cmd = $arg;
else $cmd = $cmd." ".$arg;
}
  
fputs($this->sock, $cmd."\r\n");
$this->smtp_debug("> ".$cmd."\n");
  
return $this->smtp_ok();
}
  
function smtp_error($string)
{
$this->log_write("Error: Error occurred while ".$string.".\n");
return FALSE;
}
  
function log_write($message)
{
$this->smtp_debug($message);
  
if ($this->log_file == "") {
return TRUE;
}
  
$message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
$this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n");
return FALSE;
}
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);
  
return TRUE;
}
  
function strip_comment($address)
{
$comment = "\\([^()]*\\)";
while (ereg($comment, $address)) {
$address = ereg_replace($comment, "", $address);
}
  
return $address;
}
  
function get_address($address)
{
$address = ereg_replace("([ \t\r\n])+", "", $address);
$address = ereg_replace("^.*<(.+)>.*$", "\\1", $address);
  
return $address;
}
  
function smtp_debug($message)
{
if ($this->debug) {
echo $message."<br>";
}
}
  
function get_attach_type($image_tag) { 
	$filedata = array();
	$img_file_con=fopen($image_tag,"r");
	unset($image_data);
	while ($tem_buffer=AddSlashes(fread($img_file_con,filesize($image_tag))))
	$image_data.=$tem_buffer;
	fclose($img_file_con);
	$filedata['context'] = $image_data;
	$filedata['filename']= basename($image_tag);
	$extension=substr($image_tag,strrpos($image_tag,"."),strlen($image_tag)-strrpos($image_tag,"."));
	switch($extension){
		case ".gif":
		$filedata['type'] = "image/gif";
		break;
		case ".gz":
		$filedata['type'] = "application/x-gzip";
		break;
		case ".htm":
		$filedata['type'] = "text/html";
		break;
		case ".html":
		$filedata['type'] = "text/html";
		break;
		case ".jpg":
		$filedata['type'] = "image/jpeg";
		break;
		case ".tar":
		$filedata['type'] = "application/x-tar";
		break;
		case ".txt":
		$filedata['type'] = "text/plain";
		break;
		case ".zip":
		$filedata['type'] = "application/zip";
		break;
		default:
		$filedata['type'] = "application/octet-stream";
		break;
	} 
	return $filedata;
}
}  
function verifyEmail($str){
    // $pattern = '/^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/';
    //@前面的字符可以是英文字母和._- ,._-不能放在开头和结尾,且不能连续出现
    $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
    if(preg_match($pattern,$str)){
        return true;
    }else{
        return false;
    }
}
 
/**
*实例化邮件类
*/ 
$smtpserver = "smtp.qq.com";              //SMTP服务器
$smtpserverport =25;                      //SMTP服务器端口
$smtpusermail = "2843856817@qq.com";      //SMTP服务器的用户邮箱
$smtpuser = "username";         //SMTP服务器的用户帐号
$smtppass = "password";                 //SMTP服务器的用户密码
$mailsubject = "阿里云监控测试系统";        //邮件主题
$mailsubject = "=?UTF-8?B?".base64_encode($mailsubject)."?=";    //标题转码,防止foxmail客户端乱码
$mailbody = "<h1>你的用户名是张三,密码是123147mcl </h1>";      //邮件内容
$mailtype = "HTML";                      //邮件格式(HTML/TXT),TXT为文本邮件
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);
$smtp->debug = false;                     //是否显示发送的调试信息 
?>

将发送独立出来是方便修改参数,如需修改邮件主题等,可以将变量增加到send.php里面即可

send.php

<?php
include 'mail.php';
$content = '中文标题test';
$smtpemailto = 'm@huangwx.cn';
$mailbody = "<h1>{$content}</h1><br /><h2>Powered by <a href='http://www.huangwx.cn'>微凉</a><h2>";      //邮件内容
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>

 

照常奉上长期有效的阿里云优惠:点我领取

企业高性能云首购5折:点我点我

突发性实例特价,1核1G,1年仅需293:点我查看

目录
相关文章
|
安全 Java PHP
PHP/JAVA交易所系统开发(成熟案例)丨需求步骤丨指南详细丨方案逻辑丨逻辑教程丨源码功能
An exchange refers to an institution or platform that provides a centralized market for buying and selling transactions, where participants can trade various assets, such as securities, commodities, cryptocurrencies, etc. Exchanges provide market infrastructure and rules to facilitate compliant, saf
|
2月前
|
设计模式 数据库连接 PHP
PHP中的设计模式:提升代码的可维护性与扩展性在软件开发过程中,设计模式是开发者们经常用到的工具之一。它们提供了经过验证的解决方案,可以帮助我们解决常见的软件设计问题。本文将介绍PHP中常用的设计模式,以及如何利用这些模式来提高代码的可维护性和扩展性。我们将从基础的设计模式入手,逐步深入到更复杂的应用场景。通过实际案例分析,读者可以更好地理解如何在PHP开发中应用这些设计模式,从而写出更加高效、灵活和易于维护的代码。
本文探讨了PHP中常用的设计模式及其在实际项目中的应用。内容涵盖设计模式的基本概念、分类和具体使用场景,重点介绍了单例模式、工厂模式和观察者模式等常见模式。通过具体的代码示例,展示了如何在PHP项目中有效利用设计模式来提升代码的可维护性和扩展性。文章还讨论了设计模式的选择原则和注意事项,帮助开发者在不同情境下做出最佳决策。
|
4月前
|
SQL 存储 安全
PHP 与现代 Web 应用的安全挑战与解决方案
随着 Web 应用的发展,PHP 作为一种广泛使用的服务器端脚本语言,面临着越来越复杂的安全挑战。本文探讨了当前 PHP 开发中常见的安全问题,并提供了相应的解决方案,帮助开发者构建更安全可靠的 Web 应用。 【7月更文挑战第8天】
71 1
|
1月前
|
设计模式 SQL 安全
PHP中的设计模式:单例模式的深入探索与实践在PHP开发领域,设计模式是解决常见问题的高效方案集合。它们不是具体的代码,而是一种编码和设计经验的总结。单例模式作为设计模式中的一种,确保了一个类仅有一个实例,并提供一个全局访问点。本文将深入探讨单例模式的基本概念、实现方式及其在PHP中的应用。
单例模式在PHP中的应用广泛,尤其在处理数据库连接、日志记录等场景时,能显著提高资源利用率和执行效率。本文从单例模式的定义出发,详细解释了其在PHP中的不同实现方法,并探讨了使用单例模式的优势与注意事项。通过对示例代码的分析,读者将能够理解如何在PHP项目中有效应用单例模式。
|
1月前
|
云安全 存储 小程序
PHP微信小程序解决方案PhpMall
PHP微信小程序解决方案PhpMall
39 0
|
6月前
|
缓存 NoSQL PHP
【PHP 开发专栏】Redis 作为 PHP 缓存的解决方案
【4月更文挑战第30天】本文探讨了Redis作为PHP缓存的优势,如高性能、丰富数据结构、数据持久化和分布式支持。通过安装配置Redis、选择PHP客户端、执行读写操作及制定缓存策略实现缓存。应用场景包括页面、数据和会话缓存。但需注意数据一致性、过期时间、容量和安全问题,以确保应用稳定和安全。Redis能有效提升PHP应用响应速度和处理能力。
149 2
|
PHP
php开发实战分析(4):php调用封装函数包含文件路径自适应不同目录的解决方案($_SERVER[‘DOCUMENT_ROOT‘]与__DIR__魔术常量)
php开发实战分析(4):php调用封装函数包含文件路径自适应不同目录的解决方案($_SERVER[‘DOCUMENT_ROOT‘]与__DIR__魔术常量)
178 0
|
SQL JSON 关系型数据库
php执行语句在MySQL批量插入大数据量的解决方案及计算程序执行时间(大数据量、MySQL语句优化)
php执行语句在MySQL批量插入大数据量的解决方案及计算程序执行时间(大数据量、MySQL语句优化)
272 1
|
自然语言处理 安全 Java
JAVA丨PHP交易所源码,JAVA/PHP交易所系统开发稳定版/多语言/海外版/多版本/成熟技术/方案详细/逻辑功能/规则案例
Identify requirements and design the system: Clarify your business requirements and design the architecture and functionality of the system. This includes determining the supported transaction types, user authentication, transaction matching engines, order management, fund management, etc.
PHP报错Call to undefined function utf8_decode()的解决方案
PHP报错Call to undefined function utf8_decode()的解决方案
138 0