Thursday, May 24, 2007

Gởi mail trong PHP

Trong PHP ta có thể gởi mail theo hai cách, cách 1 dùng hàm có sẵn của PHP, cách nầy đơn giản dễ hiểu, cách 2 là gỡi mail dùng smtp để gởi. Các 1 thường bị một số server ngăn không cho dùng (vì sợ bị web admin dùng cho việc phát tán thư rác) cách 2 phức tạp hơn.
Cách 1: bạn tham khảo ở đây : http://www.diendantinhoc.net/tute/webdev/php/php_by_examples/basic/tute_send_email.php
Trong tutorial nầy tôi chỉ hướng dẫn cách 2 dùng smtp.
Send mail với SMTP:
Trước tiên bạn download file class.phpmailer.php từ trang web http://phpmailer.sourceforge.net/ gói dành cho linux http://sourceforge.net/project/downloading.php?groupname=phpmailer&filename=phpmailer-1.73.tar.gz&use_mirror=jaist
unzip tất nhiên :)
Giả sử bạn đã có một tài khoản mail smtp thường có sẵn hoặt bạn tạo mới khi bạn mua host linux, hoặt là bạn được công ti cấp một email account cũng được.
ví dụ của tôi là
Host = mail.ongkhoi.com // SMTP servers
username = nha@ongkhoi.com
password = quangcao

và sau đây là code:
require("class.phpmailer.php");
require("class.smtp.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "mail.ongkhoi.com"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "nha@ongkhoi.com"; // SMTP username
$mail->Password = "quangcao"; // SMTP password
$mail->From = "nhakhtn@gmail.com";
$mail->FromName = "Mailer";
$mail->AddAddress($email,"Thanh vien"); //$email là địa chỉ email mà bạn muốn gởi
$mail->AddReplyTo("nha@ongkhoi.com","Information");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$subject = 'Kích hoạt tài khoản tại quangcao1.com ! / Kich hoat tai khoan tai quangcao1.com';
$message = "hihi test thui nhe";
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = "";
if(!$mail->Send())
{
echo "Message was not sent

";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
Hết :)

3 comments:

Anonymous said...

Hi ban! Minh` đã thử code của bạn và thấy có lỗi như sau:
"Message was not sentMailer Error: Language string failed to load: from_failedlong@rongachau.com" ??
Là sao bạn, bạn có thể giải thích ko?

Anonymous said...

Đó là do địa chỉ mail người nhận không hợp lệ, hay không đúng.
ngoài ra bạn cần include thêm tập tin class.smtp.php

Trần Thị Khánh Vũ said...

Mình cũng bị tương tự bạn trên, địa chỉ mail hợp lệ, include class đầy đủ. Nếu mình sửa lại from mail có phần sau giống server name thì ok, có thể do server ko cho nhận mail khác domain. VD servername: mail.penwoodtech.com, from mail: kv@penwoodtech.com thì ok, còn kv@yahoo.com thì lỗi như trên.