2009年7月27日 星期一

使用PHP網頁發送Mail(By PHPMailer)

先下載PHPMailer ( 官方下載網址 ) ,解壓縮至網頁資料夾。

建立PHP網頁,下例為MailSend.php

以下插入<head>中

<?php
if ($_POST[MailTitle]){
//載入PHPMailer
require_once("phpmailer/class.phpmailer.php");

$SendTo = "";
$SendTo = $_POST["MailTo"];
$SendNum = "公告已送出!共送出 " . substr_count($SendTo, '@') . " 封";

//建立Mail
$mail = new PHPMailer();

//設定發送
//$mail->IsSMTP();
$mail->Mailer = "mail";
//寄件人
$mail->From = "send@mail.com.tw";
//寄件人名稱
$mail->FromName = "SENDER";
//密件副本收件者
$mail->AddBCC($SendTo);
//回信Email及名稱
$mail->AddReplyTo("send@mail.com.tw", "SENDER");
//設定編碼
$mail->CharSet="utf-8";
//設定信件編碼
$mail->Encoding = "base64";
//設置郵件格式為HTML
$mail->IsHTML(true);
//每50字換行
$mail->WordWrap = 50;

if (is_uploaded_file($_FILES['AttFile']['tmp_name']))
{
$AtF = $_FILES['AttFile']['name'];
}else {
}
//傳送附檔
$mail->AddAttachment($_FILES['AttFile']['tmp_name'], $AtF);
//郵件標題
$mail->Subject= $_POST["SendClass"] . $_POST["MailTitle"];
//郵件內容
$mail->Body ="
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">
</head>
<body>
" . ereg_replace("\n", "<BR>\n", $_POST["MailBody"]) . "
</body>
</html>
";

//附加內容
$mail->AltBody = $_POST["MailBody"];

//寄送郵件
if(!$mail->Send())
{
echo "郵件無法順利寄出!";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
if ($_FILES['AttFile']['tmp_name'])
{
unlink($_FILES['AttFile']['tmp_name']);
}
?>
<script labguage="javascript">
alert("<?php echo $SendNum; ?>");
</script>
<?php
}else{
}
?>


以下插入<body>中

<form action="MailSend.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<table width="400" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" height="50" nowrap="nowrap">
<strong>收件者:</strong>
</td>
<td width="300" nowrap="nowrap">
<label>
<input name="MailTo" type="text" id="MailTo" size="47" />
</label>
</td>
</tr>
<tr>
<td width="100" height="50" nowrap="nowrap">
<strong>標題:</strong>
</td>
<td width="300" nowrap="nowrap">
<label>
<select name="SendClass" id="SendClass">
<option value="[公告]">[公告]</option>
<option value="[通知]">[通知]</option>
<option value="">自訂</option>
</select>
</label>
<label>
<input name="MailTitle" type="text" id="MailTitle" size="47" />
</label>
</td>
</tr>
<tr>
<td width="100" nowrap="nowrap">
<strong>內文:</strong>
</td>
<td width="300">
<label>
<textarea name="MailBody" id="MailBody" cols="50" rows="5"></textarea>
</label>
</td>
</tr>
<tr>
<td nowrap="nowrap">
<strong>附件:</strong>
</td>
<td width="300"><label>
<input type="file" name="AttFile" id="AttFile" />
</label>
</td>
</tr>
</table>
<label>
<input type="submit" name="MailSend" id="MailSend" value="送出" />
</label>
</form>

2 意見:

匿名 提到...

請問mis大大這可用來當網頁問卷調查用嗎?

Yow 提到...

可以呀~可以把網頁的表單內容送到你設定的MAIL

##EasyReadMore##