使用PHPMailer发送邮件实例代码总结
来源:程序员人生 发布时间:2014-05-24 23:46:39 阅读次数:2232次
PHPMailer发送邮件现在php开发者比较常用的一个邮件发送组件了,利用它我们几乎不需要考虑任何问题,只要简单的把代码放网上把邮箱用户名密码与stmp改一下就可以发邮件了.
PHPMailer是别人封装好的一个发送邮件的库,用起来很方便,其支持mail、sendmail和smtp的方式可以到https://code.google.com/a/apache-extras.org/p/phpmailer/downloads/list去下载最新版本的,下面通过gmail smtp发送邮件为例来说明smtp使用方法.
- function sendMail($subject, $body, $to, $ccs = array()) {
- require_once './class.phpmailer.php';
- $mail = new PHPMailer();
-
- $mail->CharSet = 'UTF-8';
-
- $mail->IsSMTP();
-
- $mail->SMTPAuth = TRUE;
-
- $mail->SMTPSecure = "ssl";
-
- $mail->Host = 'smtp.gmail.com';
-
- $mail->Port = 465;
-
- $mail->Username = 'yourgmailaccount@gmail.com';
- $mail->Password = "yourpassword";
-
- $mail->SetFrom('yourgmailaccount@gmail.com', 'display name');
-
- $mail->Subject = $subject;
-
- $mail->MsgHTML($body);
-
- $mail->AddAddress($to);
-
- foreach ($ccs as $cc) {
- $mail->AddCC($cc);
- }
- if(!$mail->Send()) {
- echo "error info:" . $mail->ErrorInfo;
- }
- }
上面是核心代码,下面我们综合一下实例,按如下示例编写代码即可实现php在线发送邮件.
一:前台表单,代码如下:
- <html>
- <body>
- <h3>phpmailer Unit Test</h3>
- 请你输入<font color="#FF6666">收信</font>的邮箱地址:
- <form name="phpmailer" action="send.php" method="post">
- <input type="hidden" name="submitted" value="1"/>
- 邮箱地址: <input type="text" size="50" name="address" />
- <br/>
- <input type="submit" value="发送"/>
- </form>
- </body>
- </html>
二:后台PHP程序,代码如下:
- <?php
- require("class.phpmailer.php");
- $mail = new PHPMailer();
- $address = $_POST['address'];
- $mail->IsSMTP();
- $mail->Host = "mail.xxxxx.com";
- $mail->SMTPAuth = true;
- $mail->Username = "user@xxxx.com";
- $mail->Password = "******";
- $mail->From = "user@xxxx.com";
- $mail->FromName = "您的名称";
- $mail->AddAddress("$address", "");
-
-
-
- $mail->Subject = "PHPMailer测试邮件";
- $mail->Body = "Hello,这是测试邮件";
- $mail->AltBody = "This is the body in plain text for non-HTML mail clients";
- if(!$mail->Send())
- {
- echo "邮件发送失败. <p>";
- echo "错误原因: " . $mail->ErrorInfo;
- exit;
- }
- echo "邮件发送成功";
- ?>
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠