繁体   English   中英

尝试使用带有 office 365 oauth2 accesstoken 的 swiftmailer 发送邮件时,在 smtp 上无法验证错误

[英]Getting Failed to authenticate error on smtp when trying to send mail using swiftmailer with office 365 oauth2 accesstoken

我正在尝试使用未能通过身份验证的 swiftmailer 和 office 365 发送邮件。 我购买了office 365账号,订阅号azure。 我的环境是php,我做的步骤:

  1. 创建 Office 365 帐户
  2. 在公元 Azure 年创建了一个应用程序
  3. 创建客户秘密
  4. 将身份验证设置为“任何组织目录中的帐户(任何 Azure AD 目录 - 多租户)”
  5. 设置 API 权限
  6. 下载Microsoft Graph sdk生成accessToken
  7. 我生成了 accesstoken 并在 swiftmailer 传输上使用它作为密码并将身份验证类型设置为“XOAUTH2”

这是支持上述活动的屏幕截图列表。

认证设置

API 权限

我使用以下来自“https://github.com/microsoftgraph/msgraph-sdk-php”的示例代码来获取访问令牌。

    $guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
    'form_params' => [
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'scope' => 'https://graph.microsoft.com/.default',
        'grant_type' => 'client_credentials',
    ],
])->getBody()->getContents());
$accessToken = $token->access_token;

下面是完整的代码

require_once 'swift/vendor/autoload.php';
require_once 'graph/vendor/autoload.php';




$tenant_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$clientSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
//$graphMailer = new graphMailer($tenant_id, $client_id, $secret_id);

$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenant_id . '/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
    'form_params' => [
        'client_id' => $client_id,
        'client_secret' => $clientSecret,
        'scope' => 'https://graph.microsoft.com/.default',
        'grant_type' => 'client_credentials',
    ],
])->getBody()->getContents());
$accessToken = $token->access_token;


// echo $accessToken;




$transport = (new Swift_SmtpTransport('smtp.office365.com', 587, 'tls'))
    ->setAuthMode('XOAUTH2')
   ->setUsername('sender@Testmail699.onmicrosoft.com')
    ->setPassword($accessToken)
;

$transport->start();

$mailer = new Swift_Mailer($transport);

$message = (new Swift_Message('Wonderful Subject'))
  ->setFrom(['sender@Testmail699.onmicrosoft.com' => 'Anish V M'])
  ->setTo(['toaddresss@gmail.com', 'toaddresss@gmail.com' => 'Anish'])
  ->setBody('Here is the message itself')
  ;

// Send the message
$result = $mailer->send($message);

echo $result;

我想知道是否有人能指出我正确的方向。 或者告诉我,如果我错过了什么。

谢谢

在我的 WHM root 登录上禁用一项设置为我解决了smtp 上的身份验证失败错误

WHM >主页>服务器配置>调整设置>
将传出 SMTP 限制为 root、exim 和 mailman(FKA SMTP 调整)[?]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM