首页 > 解决方案 > 尝试使用 Swiftmailer 发送电子邮件

问题描述

我一直在努力通过 PHP 函数向新用户发送验证电子邮件四天。然后我尝试发送一封简单的电子邮件!

只需要澄清几点:

在那之前,这个脚本仍然不起作用:

<?php

require 'dev.php';

require 'C:wamp64/www/dayou_php/vendor/autoload.php';


echo 'Envoi de mail avec Swift Mailer';

$subject = 'Mon premier email avec Swift Mailer';

$fromEmail = 'sixxerxxre@gmail.com';

$fromUser = '思而惹';

$body = '<!DOCTYPE html>
<html>
<head>
<title>Mon premier mail</title>
</head>
<body>
<h5>Hello SwiftMailer</h5>
</body>
</html>';


$transport = (new Swift_SmtpTransport(EMAIL_HOST, EMAIL_PORT))

->setUsername(EMAIL_USERNAME)

->setPassword(EMAIL_PASSWORD)

->setEncryption(EMAIL_ENCRYPTION) //For Gmail

;


// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);


// Create a message

 $message = (new Swift_Message($subject))

->setFrom([$fromEmail => $fromUser])

->setTo([EMAIL_USERNAME])

->setBody($body, 'text/html')

;


 // Send the message

$result = $mailer->send($message);

变量在另一个脚本dev.php中:

const EMAIL_HOST = 'smtp.gmail.com';

// autre port possibles : 465 pour ssl

const EMAIL_PORT = 587;
const EMAIL_USERNAME = 'my_username_without_@gmail';

const EMAIL_PASSWORD = 'my_pass_word';

// autre possibilité : ssl ou null

const EMAIL_ENCRYPTION = 'tls';

我得到的错误是关于常量my_username_without_@gmail

Address in mailbox given [seeergefaure] does not comply with RFC 2822, 3.6.2. in C:\wamp64\www\dayou_php\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Mime\Headers\MailboxHeader.php on line 355

标签: phpformsvalidationswiftmailer

解决方案


我们必须将用户名或完整地址的名称放在 gmail 服务器上吗?几声铃声……

您需要使用@gmail.com 填写全名

谁能用几句话向我解释“$ message =(new \ Swift_Message('Email Through Swift Mailer'))”行中的\?

这是关于名称空间的。这意味着,您使用全局命名空间(它将在您的自动加载器中使用)。

define ('EMAIL', 'constant;: 这个函数是否适用于 PDO 和 php 7?似乎使用 const EMAIL_USERNAME = 'constant'; 效果更好。

define 和 const 之间的基本区别在于 const 在编译时定义常量,而 define() 在运行时定义它们。

你的代码看起来不错。


推荐阅读