首先,要下载php_mail软件包
核心代码:
index.php
<?php include "mail.php"; if (!empty($_POST['to']) && !empty($_POST['fromname']) && !empty($_POST['title']) && !empty($_POST['content'])) { send_mail($_POST['to'],$_POST['fromname'],$_POST['title'],$_POST['content']); } ?> <form action="#" method="post"> 接收人:<input type="text" name="to" /><br> 发件人昵称:<input type="text" name="fromname" /><br> 标题:<input type="text" name="title" /><br> 内容:<input type="text" name="content" style="400;height:100;" /><br> <input type="submit" value="提交" /> 注:默认是用作者的QQ邮箱发送 请注意改成自己的数据 </form>
mail.php
1 <?php 2 header("content-type:text/html;charset=utf-8"); 3 ini_set("magic_quotes_runtime",0); 4 require 'php_mail/class.phpmailer.php'; 5 require 'php_mail/class.smtp.php'; 6 7 8 function send_mail($to,$fromname,$title,$content){ 9 try { 10 $mail = new PHPMailer(true); 11 $mail->IsSMTP(); 12 $mail->CharSet='UTF-8'; //设置邮件的字符编码,这很重要,不然中文乱码 13 $mail->SMTPAuth = true; //开启认证 14 $mail->Port = 25; //端口请保持默认 15 $mail->Host = "smtp.qq.com"; //使用QQ邮箱发送 16 $mail->Username = "903215283@qq.com"; //这个可以替换成自己的邮箱 17 $mail->Password = "nelfobtugzckbdae"; //注意 这里是写smtp的授权码 写的不是QQ密码,此授权码不可用 18 //$mail->IsSendmail(); //如果没有sendmail组件就注释掉,否则出现“Could not execute: /var/qmail/bin/sendmail ”的错误提示 19 $mail->AddReplyTo("903215283@qq.com","mckee");//回复地址 20 $mail->From = "903215283@qq.com"; 21 $mail->FromName = $fromname; 22 $to = $to; 23 $mail->AddAddress($to); 24 $mail->Subject = $title; 25 $mail->Body = $content; 26 $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; //当邮件不支持html时备用显示,可以省略 27 $mail->WordWrap = 80; // 设置每行字符串的长度 28 //$mail->AddAttachment("f:/test.png"); //可以添加附件 29 $mail->IsHTML(true); 30 $mail->Send(); 31 echo '邮件已发送'; 32 33 } catch (phpmailerException $e) { 34 echo "邮件发送失败:".$e->errorMessage(); 35 } 36 37 38 return true; 39 } 40 //环境 PHP5.3亲测可用 41 ?>
效果: