關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • PHP 透過 SMTP 發送郵件

    Posted on August 20th, 2007 Sam Tang 2 comments

    PHPMailer 是一個功能豐富的函式庫,以下是用 PHPMailer 通過遠端 SMTP 認證發送郵件的例子:

    PHP:
    1. <?php
    2. // 建立 PHPMailer 物件及設定 SMTP 登入資訊
    3. require("../phpMailer/class.phpmailer.php");
    4. $mail = new PHPMailer();
    5. $mail->IsSMTP(); // send via SMTP
    6. $mail->Host = "remote.smtp.server"; // SMTP servers
    7. $mail->SMTPAuth = true; // turn on SMTP authentication
    8. $mail->Username = "me@localhost"; // SMTP username
    9. $mail->Password = "123456"; // SMTP password
    10.  
    11. $mail->From = "myemail@localhost";
    12. $mail->FromName = "My Name";
    13.  
    14. // 執行 $mail->AddAddress() 加入收件者,可以多個收件者
    15. $mail->AddAddress("to@email.com","Josh Adams");
    16. $mail->AddAddress("to2@email.com"); // optional name
    17.  
    18. $mail->AddReplyTo("jyu@aemtechnology.com","AEM");
    19.  
    20. $mail->WordWrap = 50; // set word wrap
    21.  
    22. // 執行 $mail->AddAttachment() 加入附件,可以多個附件
    23. $mail->AddAttachment("path_to/file"); // attachment
    24. $mail->AddAttachment("path_to_file2", "INF");
    25.  
    26. // 電郵內容,以下為發送 HTML 格式的郵件
    27. $mail->IsHTML(true); // send as HTML
    28. $mail->Subject = "testing email";
    29. $mail->Body = "This is the <b>HTML body</b>";
    30. $mail->AltBody = "This is the text-only body";
    31.  
    32. if(!$mail->Send())
    33. {
    34.     echo "Message was not sent <p>";
    35.     echo "Mailer Error: " . $mail->ErrorInfo;
    36.     exit;
    37. }
    38.  
    39. echo "Message has been sent";
    40. ?>


     

    2 responses to “PHP 透過 SMTP 發送郵件”

    1. 謝謝你的文章!我一直使用PERL,最近正煩著PHP發MAIL呢。

    2. 請問都照你說的用了
      我直行還是出現錯誤
      Call to undefined function send_mail() in
      請問我還需要做甚麼設定
      函數一直無法用

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word