在程序根目录,建立upload文件夹。
下载PHPMailer类。
<html>
<head>
<title>虾米大王学习使用phpmailer类完成带附件的邮件发送</title>
<style type="text/css">
.tb_left
{
text-align: right;
}
.tb_right
{
text-align: left;
}
</style>
</head>
<body>
<span>虾米大王使用SMTP发送电子邮件(带附件)</span>
<hr>
<form id="form1" name="form1" method="post" action="" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td class="tb_left">收件人:</td>
<td><input type="text" name="to" id="to"></td>
</tr>
<tr>
<td class="tb_left">主题:</td>
<td><input type="text" name="subject" id="subject"></td>
</tr>
<tr>
<td class="tb_left">内容:</td>
<td><textarea name="send_body" id="send_body" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td class="tb_left">来自:</td>
<td><input type="text" name="from" id="from"></td>
</tr>
<tr>
<td class="tb_left">附件:</td>
<td><input type="file" name="user_file" id="user_file"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="btn_sub" id="btn_sub" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
if(@ isset($_POST['btn_sub']))
{
require_once ("src/PHPMailer.php"); //必须引入此3个文件,否则出错
require_once ('src/Exception.php');
require_once ('src/SMTP.php');
$from = $_POST['from'];
$to = $_POST['to'];
$subject = $_POST['subject'];
$send_body = wordwrap($_POST['send_body'],70);
$smtp = 'smtp.163.com'; //如果使用qq邮箱,请先去邮箱开启此功能
$port = 465; //一般端口都是465
$user_name = 'name@xxx.com'; //请替换为你的邮箱,注意需要去邮箱的设置开启smtp,我使用的163.com
$password = 'password'; //请替换为你的邮箱密码
$mail = new \PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = $smtp;
$mail->Port = $port;
$mail->CharSet = 'utf-8'; //使用gb2312是,只能发送英文字母,发送中文是乱码
$mail->Username = $user_name;
$mail->Password = $password;
$mail->From = $from;
$mail->FromName = $from;
$mail->Subject = $subject;
$mail->Body = $send_body;
$mail->isHTML(true);
$mail->addAddress($to);
$upload_dir = 'upload/';
$up_file = $upload_dir.basename($_FILES['user_file']['name']);
if(move_uploaded_file($_FILES['user_file']['tmp_name'],$up_file))
{
$mail->addAttachment($up_file);
}
if(!$mail->send())
{
echo "发送错误:".$mail->ErrorInfo."<br>";
}
else
{
echo "<div align='center'>虾米大王的邮件发送成功,请注意查收!</div>";
}
die();
}
?>