Home php教程 php手册 使用php发送有附件的电子邮件-(PHPMailer使用的实例分析)

使用php发送有附件的电子邮件-(PHPMailer使用的实例分析)

Jun 13, 2016 am 11:54 AM
php phpmailer code use send copy Case Analysis have use e-mail of appendix

复制代码 代码如下:


/*PHPMailer是一个用于发送电子邮件的PHP函数包。它提供的功能包括:
  *.在发送邮时指定多个收件人,抄送地址,暗送地址和回复地址
  *.支持多种邮件编码包括:8bit,base64,binary和quoted-printable
  *.支持SMTP验证
  *.支持冗余SMTP服务器
  *.支持带附件的邮件和Html格式的邮件
  *.自定义邮件头
  *.支持在邮件中嵌入图片
  *.调试灵活
  *.经测试兼容的SMTP服务器包括:Sendmail,qmail,Postfix,Imail,Exchange等
  *.可运行在任何平台之上

phpMailer是一个非常强大的php发送邮件类,可以设定发送邮件地址、回复地址、邮件主题、富文本内容,上传附件,.....
官方网站:http://phpmailer.worxware.com/
下载地址:http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/list
*/
require_once('include/PHPMailer/class.phpmailer.php'); //导入PHPMAILER类
$mail = new PHPMailer(); //创建实例
$mail -> CharSet='utf-8'; //设置字符集
$mail -> SetLanguage('ch','include/PHPMailer/language/');  //设置语言类型和语言文件所在目录         
$mail -> IsSMTP(); //使用SMTP方式发送
$mail -> SMTPAuth = true; //设置服务器是否需要SMTP身份验证 
$mail -> Host = SMTP_SERVER; //SMTP 主机地址 
$mail -> Port = SMTP_SERVER_PORT; //SMTP 主机端口
$mail -> From = SMTP_USER_MAIL; //发件人EMAIL地址
$mail -> FromName = 'jasonxu'; //发件人在SMTP主机中的用户名 
$mail -> Username = SMTP_USER_NAME; //发件人的姓名 
$mail -> Password = SMTP_USER_PASS; //发件人在SMTP主机中的密码 
$mail -> Subject = '测试邮件的标题'; //邮件主题 
$mail -> AltBody = 'text/html'; //设置在邮件正文不支持HTML时的备用显示
$mail -> Body = '测试邮件的内容';//邮件内容做成
$mail -> IsHTML(true);  //是否是HTML邮件
$mail -> AddAddress('chinajason2008#gmail.com','jasonxu'); //收件人的地址和姓名 
$mail -> AddReplyTo('chinajason2008#gmail.com','jasonxu'); //收件人回复时回复给的地址和姓名
$mail -> AddAttachment('include/id.csv','att.csv');//附件的路径和附件名称
if(!$mail -> Send()) //发送邮件 
var_dump($mail -> ErrorInfo);  //查看发送的错误信息


注意:phpmailer如果添加附件的时候,在附件名称里一定要写明附件的后缀,如果不写明附件后缀,默认的附件后缀会是.txt。
比如$mail -> AddAttachment('include/id.csv','att');//附件的路径和附件名称
如果向上面一样添加附件发送,则最终接到的附件可能是att.txt。
AddAttachment可以设置附件编码方式和附件类型,比如上面的附件添加也可以设置为
$mail -> AddAttachment('include/id.csv','att.csv',"binary","text/comma-separated-values");//附件的路径和附件名称、
附件的编码方式大概有这么几种:支持8bit, base64, binary, and quoted-printable 编码

而CSV可接受的MIME Type
· application/octet-stream
· text/comma-separated-values(推荐)
· text/csv
所以,csv格式文件的附件类型可以是上面三种中的任意一种

以前项目中邮件发送的一个实例,整理个缩略版,方便套用:

复制代码 代码如下:


$body=$_smtp_body;
$mail=new PHPMailer();//得到一个PHPMailer实例
//$mail->SMTPSecure='tls';
$mail->CharSet="utf-8"; //设置编码
$mail->IsSMTP();//设置采用SMTP方式发送邮件
$mail->Host=$_smtp_server;//设置SMTP邮件服务器的地址
$mail->Port=$_smtp_port;//设置邮件服务器的端口,默认为25
$mail->From=$_smtp_from_mail; //设置发件人的邮箱地址
$mail->FromName=$_smtp_from_name;//设置发件人的姓名
$mail->Username=$_smtp_username;
$mail->Password=$_smtp_password;
$mail->AddAddress("$email","");//设置收件的地址(参数1)和姓名(参数2)
$mail->SMTPAuth=true;//开启SMTP认证
$mail->Subject=$_smtp_subject;//设置邮件的标题
//$mail->AltBody="text/html";
$mail->Body=$body;//邮件内容
$mail->IsHTML(true);//设置内容是否为html类型
//$mail->WordWrap=50;                                 //设置每行的字符数
//$mail->AddReplyTo("samzhang@tencent.com","samzhang");     //设置回复的收件人的地址
$mail->SMTPDebug=0;
if($mail->Send()){//发送邮件
  exit 'ok';
}else{
  exit 'fail';
}


大概记得以前初次使用PHPMailer的时候,出现过莫名奇妙的问题,也在网上花了不少时间找资料,最终才得以解决。目前记得服务器PHP环境不能禁止fsockopen函数,否则邮件发送不了,但也有解决的办法。总之,一开始使用,总有不顺,由于时间久远,现在想来,也不知道具体改了什么。所以,将现在正在使用的PHPMailer目录文件打包上传到CSDN,也为方便以后使用吧,同时也方便为此事烦恼的朋友。PHPMailer下载:http://xiazai.jb51.net/201304/yuanma/PHPMailer_jb51net.rar
另外,将当时出现的问题所收录的内容整理如下:

1、Error: Could not connect to SMTP host
原因1:不邮邮件系统要求的smtp请求不同一,但是都允许大写,有些不支持小写,比如网易,腾讯的邮箱。(至于是不是这样,我没测试过,反正都改为大写,也不影响)

解决方法:

复制代码 代码如下:


public function IsSMTP() {
  $this->Mailer ='SMTP'; // 将smtp ->SMTP ;即原来是小写,现在大写。
}

// Choose the mailer and send through it
switch($this->Mailer) {
  case 'sendmail':
    return $this->SendmailSend($header, $body);
  case 'SMTP'://同样 将smtp ->SMTP ;即原来是小写,现在大写。
    return $this->SmtpSend($header, $body);
  case 'mail':
  default:
    return $this->MailSend($header, $body);
}


2、SMTP Error: Could not connect to SMTP host
原因:有的虚拟主机,或服务器,为了安全起见屏蔽了“fsockopen()函数”导致无法发送邮件

解决方法:

启用fsockopen函数

首先,在php.ini中去掉下面的两个分号

;extension=php_sockets.dll

;extension=php_openssl.dll

 替换fsockopen函数

可以将class.smtp.php文件中fsockopen函数换成pfsockopen函数


3、Could not instantiate mail function
原因:

设置的参数不正确,我使用了gmail做一些基本测试,需要在次设置其他参数。

解决方法:

$mail->SMTPSecure = ‘tls'; //只需要加上这句

注:这种错误我没碰到过,所以在上面的例子中,这个内容我是加了注释的。如果碰到这种错误的,可以使用这句试试。

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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