SendGrid php电子邮件无法在Azure

时间:2017-02-16 18:41:38

标签: php email azure sendgrid

我正在设置一个基于Azure的网站,需要自动发送电子邮件回复。由于Azure本身不允许这样做,我尝试使用SendGrid。代码(基于他们的样本)在我自己的服务器上运行良好(它返回202状态并且电子邮件已发送),但在Azure上完全没有。这有什么原因吗?

我的代码如下:

<?php

require ("sendgrid-php/sendgrid-php.php");

$from = new SendGrid\Email("DX PHP Test", "MY EMAIL ADDRESS");
$subject = "Sending with SendGrid is Fun";
$to = new SendGrid\Email("Dorian", "MY EMAIL ADDRESS");
$content = new SendGrid\Content("text/plain", "and easy to do anywhere, even with PHP");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = "MY API KEY";
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
?>

显然,我在我的工作版本中包含了正确的API密钥和电子邮件地址。 sendgrid-php文件夹也已上传到正确的位置,正如我之前所说,它可以在我自己的服务器上运行。

我已经浏览了一下,但找不到任何专门回答这个问题的回复。如果这种方法由于某种原因不能起作用(我想知道为什么!)任何人都可以提出不同的方法吗?

编辑:建议的可能重复也不起作用!我尝试使用它时,无法识别我的SendGrid名称和/或密码。但是,this blog处的说明确实有效。这就是我所做的:

  1. 在Azure中设置SendGrid帐户,并记下在配置刀片上生成的用户名。密码与您设置SendGrid帐户的密码相同。
  2. 从Github下载PHPMailer并将PHPMailer-master文件夹解压缩到与您要运行的代码相同的文件夹中。
  3. 使用以下代码(稍微从上述博客编辑)从Azure发送电子邮件。显然,将用户名和密码更改为上面步骤1中的用户名和密码。您还需要在以“$ mail-&gt; addAddress”开头的行中添加正确的电子邮件地址,以测试其是否有效:

    <?php
    require 'PHPMailer-master/PHPMailerAutoload.php';
    
    $mail = new PHPMailer;
    
    //$mail->SMTPDebug = 3;                    // Enable verbose debug output
    
    $mail->isSMTP();                           // Set mailer to use SMTP
    $mail->Host = 'smtp.sendgrid.net';         // Specify main/backup SMTP servers
    $mail->SMTPAuth = true;                    // Enable SMTP authentication
    $mail->Username = 'SENDGRID USERNAME';     // SMTP username
    $mail->Password = 'SENDGRID PASSWORD';     // SMTP password
    $mail->SMTPSecure = 'tls';                 // Enable TLS/SSL encryption
    $mail->Port = 587;                         // TCP port to connect to
    
    $mail->From = 'email@contoso.com';
    $mail->FromName = 'From SendGrid website';
    $mail->addAddress('TEST EMAIL ADDRESS', 'A NAME'); // Add a recipient
    
    $mail->WordWrap = 50;                       // Set word wrap to 50 characters
    $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>';
    
    if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
    echo 'Message has been sent';
    }
    ?>
    

0 个答案:

没有答案