I have a local Wordpress website that sends emails successfully, however if I try to send an email from a Codeception integration test, I do not receive any emails. (By the way, I don't think the problem has to do with Wordpress, which is why I'm posting here rather than Wordpress Stack Exchange).
I've configured Wordpress like this:
add_action( "phpmailer_init", array( $this, "configure_mailer" ) );
function configure_mailer( $mailer ) {
$mailer->isSMTP();
$mailer->Host = "smtp.gmail.com";
$mailer->SMTPAuth = true;
$mailer->Username = "myemail#gmail.com";
$mailer->Password = "mypassword";
$mailer->SMTPSecure = "tls";
$mailer->Port = 587;
$mailer->IsHTML( true );
}
Now if I try to send an email with wp_mail (which internally uses a PHPMailer instance configured as above) from my Wordpress code, eg. via an API request, I do receive the email:
// This is the custom API route that sends the email
register_rest_route( "mynamespace/v1", "/send-email", [
"methods" => \WP_REST_Server::CREATABLE,
"permission_callback" => "__return_true",
"callback" => function() {
$result = wp_mail( "myemail#example.com", "Test subject", "Test message", array( "From: MySite <myemail#example.com>");
return new \WP_REST_Response( $result );
}
]);
// This is the API request
POST https://example.com/wp-json/mynamespace/v1/send-email
The above request returns true because wp_mail returns true (as it does when an email is sent successfully), and I receive the email.
If I try to send the email from a Codeception integration test, the test succeeds because wp_mail still returns true, but I do not receive the email. (The \Codeception\TestCase\WPTestCase comes from wpbrowser, a package I use for testing Wordpress with Codeception).
class EmailTest extends \Codeception\TestCase\WPTestCase {
public function testSendsEmail() {
$result = wp_mail( "myemail#example.com", "Test subject", "Test message", array( "From: MySite <myemail#mysite.com>");
$this->assertTrue( $result );
}
}
Related
I read all the other answers related to that question, but none of them help.
When I try to run the following setup either on my localhost or my production server, I get the following error message:
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
I installed CodeIgniter 4 and added the following to .env:
email.production.protocol = smtp
email.production.SMTPHost = my.server.com
email.production.SMTPUser = My#Mail.com
email.production.SMTPPass = MyPassword
email.production.SMTPCrypto = ssl
email.production.SMTPPort = 465
email.production.SMTPFromName = "Foo Bar"
For port 465 or 587 and crypto ssl or tsl I tried every possible option.
In the app/Config/Email.php the setting public $newline = "\r\n"; is already set (Suggestion coming from here.
I am successfully able to run
telnet my.server.com 465
telnet my.server.com 587
Then I added the following code to the end of app/Config/Email.php:
public function __construct()
{
$this->protocol = $_ENV['email.production.protocol'];
$this->SMTPHost = $_ENV['email.production.SMTPHost'];
$this->SMTPUser = $_ENV['email.production.SMTPUser'];
$this->SMTPPass = $_ENV['email.production.SMTPPass'];
$this->SMTPPort = $_ENV['email.production.SMTPPort'];
$this->SMTPCrypto = $_ENV['email.production.SMTPCrypto'];
$this->fromEmail = $_ENV['email.production.SMTPUser'];
$this->fromName = $_ENV['email.production.SMTPFromName'];
}
In my Controller I added a function with:
$email = \Config\Services::email();
$email->setSubject("Test");
$email->setMessage("Test");
$email->setTo("myaddress#example.com");
if ($email->send(false)) {
return $this->getResponse([
'message' => 'Email successfully send',
]);
} else {
return $this
->getResponse(
["error" => $email->printDebugger()],
ResponseInterface::HTTP_CONFLICT
);
}
Calling this function produces the error message described above.
I assume that this has nothing to do with the server configuration as the error message describes, because the is happening on localhost and production.
Update: This must have something to do with the CI setup. No matter what server I try, even with completely incorrect values (e.g. incorrect password) the error is exactly the same.
I usually use smtp gmail to send email for my client. the most important of 'send email by smtp gmail' is you must update your Gmail Security rules:
In your Gmail Account, click on Manage your Google Account
click tab Security
then, turn 'less secure app access' to 'ON'
After that, you set your 'app\config\EMail.php' like this:
public $protocol = 'smtp';
public $SMTPHost = 'smtp.gmail.com';
public $SMTPUser = 'your.googleaccount#gmail.com';
public $SMTPPass = 'yourpassword';
public $SMTPPort = 465;
public $SMTPCrypto = 'ssl';
public $mailType = 'html';
Last, you can create sendEmai function on controller like this:
$email = \Config\Services::email();
$email->setFrom('emailsender#gmail.com', 'Mr Sender');
$email->setTo('emailreceiver#gmail.com');
$email->setSubject('Test Subject');
$email->setMessage('Test My SMTP');
if (!$email->send()) {
return false;
}else{
return true;
}
i want to use config that i get from html form and i dont want to get it from config/mail.php or .env file
how can i do that in laravel 8
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($address = 'contact#example.com', $name = $this->data['from'])
->subject($this->data['subject'])
->view('mail.view')
->smtp('mail.example.com')
->port('587')
->username('username')
->password('pass')
->smtp('mail.example.com')
->with(['message' => $this->data['message']]);
}
you can use swiftmailer to send any type of mail you want (laravel use this under the hood):
$transport = (new Swift_SmtpTransport("smtp.gmail.com", "587", "tls"))
->setUsername('username')
->setPassword('pass');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message("subject")) // email subject
->setFrom(['contact#example.com' => "sender name"]) // sender mail and display name
->setTo("receiver#gmail.com") // replace with your receiver mail variable
->setBody("<h2>Test</h2>", 'text/html');
$result = $mailer->send($message); // send the mail
if you want to send from queue instead of in controller directly, you can create queue and pass mail parameter to queue construct
I'm using Yii framework while my question is probably intended to PHP expert.
I have created a controller to send email from my web application, it works fine.
Given that, I intend to use email in several sontrollers in my app, I wanted to created a helper but that does not work. Email is not sent. (I'm using swiftmailer)
The code of the working controller is the following:
<?php
class MailController extends Controller
{
/**
* Declares class-based actions.
*/
public function actionSendemail() {
// Plain text content
$plainTextContent = "This is my first line ;-)\nThis is my second row of text";
// Get mailer
$SM = Yii::app()->swiftMailer;
// New transport mailHost= localhost, mailPort = 25
$Transport = $SM->smtpTransport(Yii::app()->params['mailHost'], Yii::app()->params['mailPort']);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage('My subject')
->setFrom(array('test1#localhost.localdomain' => 'Example Name'))
->setTo(array('myemail#domain.com' => 'Recipient Name'))
// ->addPart($content, 'text/html')
->setBody($plainTextContent);
// Send mail
$result = $Mailer->send($Message);
}
}
The helper code is the following
<?php
// protected/components/Email.php
class Email {
public static function sendEmail($subject, $from, $to, $body)
{
// Get mailer
$SM = Yii::app()->swiftMailer;
// New transport
$Transport = $SM->smtpTransport(Yii::app()->params['mailHost'], Yii::app()->params['mailPort']);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage($subject)
->setFrom(array($from => 'Example Name'))
->setTo(array($to => 'Recipient Name'))
// ->addPart($content, 'text/html')
->setBody($body);
// Send mail
$result = $Mailer->send($Message);
}
}
the way I call it is the following
$subject= 'My subject';
$from = Yii::app()->params['adminEmail']; // adminEmai is a globalparam like above controller
$to='xxxx#xxx.com';
$body='my body';
Email::sendEmail($subject, $from, $to, $body);
when I run this code, I have no error, but I dont receive the email.
Thank you for your help.
I found my error.
my global parameters in config.php was not set correctly.
So content I put in the from field was not recognized by my hmailserver which is configured for the moment with the content test1#localhost.localdomain
sorry for the question and thanks
I'm having trouble investigating an 500 Internal Server Error I get when trying to do an AJAX request ( I'm doing a "PUT" / "GET" ) on my server.
Locally it runs without any issues and it responds, but after I uploaded the content on the server it doesn't, as if the file / folder wouldn't be there.
The host is running on Apache with PHP at least version 5.3.0 since I last checked. I get the error when trying to use the footer newsletter subscribe.
My index file which is requested when doing the AJAX looks like the following :
<?php
/*
* Import PHPMailer Class
*/
require("phpmailer/class.phpmailer.php");
/*
* Decode JSON Data
*/
$request = json_decode(file_get_contents("php://input"), true);
/*
* Check Valid Email Address
*/
if (!filter_var($request["Email"], FILTER_VALIDATE_EMAIL)) {
echo json_encode([
"error" => true,
"message"=> "You must enter a valid email address"
]);
return false;
};
/*
* Instantiate PHPMailer Class
*/
$mailer = new PHPMailer();
/*
* Set Reply Settings
*/
$reply_email = "no-reply#barbershoppen.dk";
$reply_name = "Barber Shoppen";
/*
* Specific PHPMailer Settings
*/
$mailer->IsSMTP(); /* SMTP Usage */
$mailer->SMTPAuth = true; /* SMTP Authentication */
$mailer->SMTPSecure = "ssl"; /* Sets Servier Prefix */
$mailer->Host = "smtp.gmail.com"; /* SMTP Server */
$mailer->Port = 465; /* SMTP Port */
$mailer->Username = "rolandeveloper#gmail.com"; /* SMTP Account Username */
$mailer->Password = "333333333"; /* SMTP Account Password */
/*
* Email Settings
*/
$mailer->SetFrom($reply_email, $reply_name);
$mailer->AddReplyTo($reply_email, $reply_name);
$mailer->AddAddress($request["Email"]);
$mailer->Subject = "Barber Shoppen [ Confirmation Email ]";
$mailer->Body = "You have successfully subscribed to our newsletter";
$mailer->isHTML(true);
/*
* Send Email
*/
if($mailer->Send()) {
echo json_encode([
"error" => false,
"message"=> "You have successfully subscribed"
]);
} else {
echo json_encode([
"error" => true,
"message"=> $mailer->ErrorInfo
]);
};
?>
I would appreciate some help or some pointers in which directions I should head and fix this error.
You want to pass in a PHP-style array instead of a javascript-style array into json_encode:
if (!filter_var($request["Email"], FILTER_VALIDATE_EMAIL)) {
echo json_encode(array(
"error" => true,
"message"=> "You must enter a valid email address"
));
return false;
};
And:
if($mailer->Send()) {
echo json_encode(array(
"error" => false,
"message"=> "You have successfully subscribed"
));
} else {
echo json_encode(array(
"error" => true,
"message"=> $mailer->ErrorInfo
));
};
Have read this and this and using example from here.
However, I am still having difficulty in sending emails as a verified Google user using OAuth. I have the valid OAuth tokens, secrets, and xoauth token as well.
My code to send the email:
$authenticateParams = array('XOAUTH', $initClientRequestEncoded);
$smtp = new Zend_Mail_Protocol_Smtp('smtp.gmail.com', 587, array(
"AUTH" => $authenticateParams, 'ssl' => 'tls'));
try {
// Create a new mail object
$mail = new Zend_Mail();
$mail->setFrom("aaaaa#gmail.com");
$mail->addTo("bbbbb#gmail.com");
$mail->setSubject("Your account has been created");
$email = "Thank you for registering!";
$mail->setBodyText($email);
$mail->send();
} catch (Exception $e) {
echo "error sending email . <BR>" . $e;
}
But this seems to send an anonymous email and not as the user authenticated. If I do:
$smtp = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array('AUTHENTICATE' => $authenticateParams, 'ssl' => 'tls'));
Zend_Mail::setDefaultTransport($smtp);
I get: exception 'Zend_Mail_Protocol_Exception' with message '5.5.1 Authentication Required.
I'm sure it's just a case of getting the mail transport smtp params right, but the documentation for sending SMTP emails is non-existent and I can't find any code examples for this.
Check out the following blog posts which will show you where you went wrong.
google smtp oauth2 authentication
send mail with gmail smtp and xoauth