簡體   English   中英

從 SMTP 服務器發送 email 和 PHP

[英]Sending email with PHP from an SMTP server

$from = "someonelse@example.com";
$headers = "From:" . $from;
echo mail ("borutflis1@gmail.com" ,"testmailfunction" , "Oj",$headers);

我在 PHP 中發送 email 時遇到問題。我收到錯誤消息: SMTP server response: 530 SMTP authentication is required

我的印象是您可以發送 email 而無需 SMTP 進行驗證。 我知道這封郵件可能會被過濾掉,但現在這並不重要。

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = someonelse@example.com

這是php.ini文件中的設置。 我應該如何設置SMTP? 有沒有SMTP服務器不需要驗證或者必須自己架設服務器?

當您通過需要 SMTP 身份驗證的服務器發送電子郵件時,您確實需要指定它,並設置主機、用戶名和密碼(如果不是默認端口,還可以設置端口 - 25)。

例如,我通常使用與以下設置類似的 PHPMailer:

$mail = new PHPMailer();

// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';

$mail->Host       = "mail.example.com";    // SMTP server example
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
$mail->Username   = "username";            // SMTP account username example
$mail->Password   = "password";            // SMTP account password example

// Content
$mail->isHTML(true);                       // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();

您可以在此處找到有關 PHPMailer 的更多信息: https : //github.com/PHPMailer/PHPMailer

<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL@gmail.com");

$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = YourMail@address.com";

$headers = "From: YOURMAIL@gmail.com";

mail("Sending@provider.com", "Testing", $message, $headers);
echo "Check your email now....&lt;BR/>";
?>

或者,有關更多詳細信息, 請繼續閱讀

對於 Unix 用戶,mail() 實際上是使用Sendmail命令發送電子郵件。 您可以更改環境而不是修改應用程序。 msmtp是具有 Sendmail 兼容 CLI 語法的 SMTP 客戶端,這意味着它可以代替 Sendmail 使用。 它只需要對您的 php.ini 稍作改動。

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

那么即使是低級的 mail() 函數也可以與 SMTP 的優點一起工作。 如果您嘗試將現有應用程序連接到 sendgrid 或 mandrill 等郵件服務而不修改應用程序,這將非常有用。

這是一種使用 PHP PEAR 實現的方法

// Pear Mail Library
require_once "Mail.php";

$from = '<your@mail.com>'; //change this to your email address
$to = '<someone@mail.com>'; // change to address
$subject = 'Insert subject here'; // subject of mail
$body = "Hello world! this is the content of the email"; //content of mail

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com',
        'port' => '465',
        'auth' => true,
        'username' => 'your@gmail.com', //your gmail account
        'password' => 'snip' // your password
    ));

// Send the mail
$mail = $smtp->send($to, $headers, $body);

//check mail sent or not
if (PEAR::isError($mail)) {
    echo '<p>'.$mail->getMessage().'</p>';
} else {
    echo '<p>Message successfully sent!</p>';
}

如果您使用 Gmail SMTP 請記住在您的 Gmail 帳戶中啟用 SMTP,在設置下

編輯:如果你在 debian/ubuntu 上找不到 Mail.php,你可以安裝 php-pear

sudo apt install php-pear

然后安裝郵件擴展:

sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime

然后你應該可以通過簡單的require_once "Mail.php"加載它,否則它位於: /usr/share/php/Mail.php

問題是 PHP mail()函數的功能非常有限。 有幾種方法可以從 PHP 發送郵件。

  1. mail()在您的系統上使用 SMTP 服務器。 您至少可以在 Windows 上使用兩個服務器: hMailServerxmail 我花了幾個小時來配置和安裝它們。 在我看來,第一個更簡單。 現在,hMailServer 正在 Windows 7 x64 上運行。
  2. mail()在 Linux 的遠程或虛擬機上使用 SMTP 服務器。 當然,像 Gmail 這樣的真實郵件服務不允許在沒有任何憑據或密鑰的情況下直接連接。 您可以設置虛擬機或使用位於 LAN 中的虛擬機。 大多數 linux 發行版都有開箱即用的郵件服務器。 配置它並玩得開心。 我在 Debian 7 上使用默認的 exim4 來監聽它的 LAN 接口。
  3. 郵件庫使用直接連接。 Libs 更容易設置。 我使用了 SwiftMailer,它完美地從 Gmail 帳戶發送郵件。 我認為 PHPMailer 也很不錯。

無論您的選擇是什么,我都建議您使用一些抽象層。 您可以在運行 Windows 的開發機器上使用 PHP 庫,並在使用 Linux 的生產機器上使用mail()函數。 抽象層允許您根據應用程序運行的系統交換郵件驅動程序。 使用抽象的send()方法創建抽象的MyMailer類或接口。 繼承兩個類MyPhpMailerMySwiftMailer 以適當的方式實現send()方法。

有一些 SMTP 服務器無需身份驗證即可工作,但如果服務器需要身份驗證,則無法繞過。

PHP 的內置郵件功能非常有限 - 只能在 WINdows 中指定 SMTP 服務器。 在 *nix 上, mail()將使用操作系統的二進制文件。

如果您想將電子郵件發送到網絡上的任意 SMTP 服務器,請考慮使用像SwiftMailer這樣的庫。 例如,這將使您能夠使用 Google Mail 的外發服務器。

如果您在 Linux 上托管WordPress站點並具有服務器訪問權限,您可以通過安裝 msmtp 來避免一些麻煩,它允許您從標准的 PHP mail() 函數通過SMTP發送。 msmtp 是 postfix 的一個更簡單的替代方案,它需要更多的配置。

以下是步驟:

安裝 msmtp

sudo apt-get install msmtp-mta ca-certificates

創建一個新的配置文件:

sudo nano /etc/msmtprc

...具有以下配置信息:

# Set defaults.
defaults

# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <username@example.net>
password <password>
from <address-to-receive-bounces@example.net>
syslog LOG_MAIL

您需要替換由“<”和“>”中的所有內容表示的配置數據(包括,刪除這些)。 對於主機/用戶名/密碼,使用您的普通憑據通過郵件提供商發送郵件。

告訴 PHP 使用它

sudo nano /etc/php5/apache2/php.ini

添加這一行:

sendmail_path = /usr/bin/msmtp -t

完整的文檔可以在這里找到:

https://marlam.de/msmtp/

對於另一種方法,您可以采用這樣的文件:

From: Sunday <sunday@gmail.com>
To: Monday <monday@gmail.com>
Subject: Day

Tuesday Wednesday

並像這樣發送:

<?php
$a1 = ['monday@gmail.com'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);

https://php.net/function.curl-setopt

如果有人需要,我為 PHP 創建了一個簡單的輕量級 SMTP 電子郵件發送器。 這是網址:

https://github.com/jerryurenaa/EZMAIL

它在生產環境和開發環境中都經過了測試。

我知道這是一個老問題,但它仍然有效,我看到的所有答案都顯示了基本身份驗證,這已被棄用。 下面是一個示例,展示了如何使用帶有 XOAUTH2 身份驗證的 PHPMailer 通過 Google 的 Gmail 服務器進行發送:

//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer();

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';

//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;

//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';

//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone@gmail.com';
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';

//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';

//Create a new OAuth2 provider instance
$provider = new Google(
    [
        'clientId' => $clientId,
        'clientSecret' => $clientSecret,
    ]
);

//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
    new OAuth(
        [
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,
            'userName' => $email,
        ]
    )
);

//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');

//Set who the message is to be sent to
$mail->addAddress('someone@gmail.com', 'John Doe');

//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.html'), __DIR__);

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}

參考: PHPMailer 示例文件夾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM