Home Backend Development PHP Tutorial 使用php发送有附件的电子邮件-(PHPMailer使用的实例分析)_php实例

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

Jun 07, 2016 pm 05:24 PM
php phpmailer

复制代码 代码如下:

/*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.php.net/201304/yuanma/PHPMailer_phpnet.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 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 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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.

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.

See all articles