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;
}
Related
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 );
}
}
My laravel project php mailer function is working in local host. But in the live server it's not working:
Error:
FatalThrowableError in RegisterController.php line 75:
Class 'App\CustomClass\CMailer' not found
Here is my controller file:
enter code here
<?php
namespace App\Http\Controllers\Auth;
use App\CustomClass\CMailer;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:4|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
if ($user) {
$mailException = null;
$view = view('auth.verification', compact('user'))->render();
try {
$mail = CMailer::send('Prapti', $data['email'], 'Email verification', $view);
} catch (Exception $e) {
$mailException = true;
}
}
return $user;
}
}
enter code here
My class file:
enter code here
namespace App\CustomClass;
use PHPMailer\PHPMailer\PHPMailer;
class CMailer
{
protected static $host = "smtp.gmail.com";
protected static $port = 468;
protected static $encryption = 'tls';
protected static $username = "******";
protected static $password = '***************';
protected static $from = '**************#gmail.com';
/**
* Sending email by PHPMailer
*
* #param string $fromName
* #param string $to
* #param string $subject
* #param string $message
* #return TRUE
*/
public static function send($fromName, $to, $subject, $message)
{
$mail = new PHPMailer(true);
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = self::$host;
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = self::$port;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = self::$encryption;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for
gmail
$mail->Username = self::$username;
//Password to use for SMTP authentication
$mail->Password = self::$password;
//Set who the message is to be sent from: this is sender email
$mail->setFrom(self::$from, $fromName);
//Set who the message is to be sent to
$mail->addAddress($to, 'Test Service');
//Set the subject line
$mail->Subject = $subject;
$mail->msgHTML($message);
if (!$mail->send()) {
// return $mail;
return false;
} else {
return true;
}
}
}
** Php mailer and class is okay. I've tested by changing port but same problem. and not working in hosting. Where is the problem?
Please suggest me the solution.
You need to run composer dump-autoload to reload all missing classes.
If the same code works on your local machine, you need to run composer du command on the live server and include this command to your deployment script.
Is there something I'm missing? I've searched high, and low, and I'm not sure what's wrong with my code. Also is it that I'm using public, rather than mail?
<?php
require_once('phpmailer.php');
class Mail extends PhpMailer
{
// Set default variables for all new objects
public $mail = IsSMTP;
public $From = 'register#lolvoid.net23.net';
public $FromName = SITETITLE;
public $Host = 'smtp.gmail.com';
public $port = 587;
public $Mailer = 'smtp';
public $SMTPAuth = true;
public $Username = 'email#gmail.com';
public $Password = 'password';
public $SMTPSecure = 'tls';
public $WordWrap = 75;
public function subject($subject)
{
$this->Subject = $subject;
}
public function body($body)
{
$this->Body = $body;
}
public function send()
{
$this->AltBody = strip_tags(stripslashes($this->Body))."\n\n";
$this->AltBody = str_replace(" ", "\n\n", $this->AltBody);
return parent::send();
}
}
This is my current code, and the issue hasn't been resolved. Any new ideas?
Change port to secured one for SMTP: 465
Port should be 587 instead of 4587.
Here are the default Gmail SMTP settings;
Gmail SMTP server address: smtp.gmail.com
Gmail SMTP username: Your
full Gmail address (e.g. yourusername#gmail.com)
Gmail SMTP password: Your Gmail password
Gmail SMTP port (TLS): 587
Gmail SMTP port (SSL): 465
Gmail SMTP TLS/SSL required: yes
and could you please change the line
public $mail = 'IsSMTP()'
with the following:
public $mail = IsSMTP();
Most probably a port.
public $port = '4587';
if you tried configuring your SMTP server on port 465 (with SSL/TLS)
and port 587 (with STARTTLS), but are still having trouble sending
mail, try configuring your SMTP to use port 25 (with SSL/TLS).
Apple Mail users: At times, Mail may misinterpret your SMTP server
settings. If you currently have 'smtp.gmail.com:username#gmail.com' in
the 'Outgoing Mail Server:' field of your settings, please try
changing the field to 'smtp.gmail.com' and saving your settings.
https://support.google.com/mail/answer/78775?hl=en
You mixed 465 and 587 ports.
If it still does not work, you can try debugging connection. See PHPMailer only sends email when SMTPDebug = true for example.
Also, from documentation:
/**
* SMTP class debug output mode.
* Debug output level.
* Options:
* * `0` No output
* * `1` Commands
* * `2` Data and commands
* * `3` As 2 plus connection status
* * `4` Low-level data output
* #var integer
* #see SMTP::$do_debug
*/
public $SMTPDebug = 0;
Use it to find out what problem may be. It will tell you where it stops.
I am trying to send email using Zend Smtp.
I have configured everything with zend and with my credential of google.
When I try to send a mail i am getting this error.
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
I am not sure what the mistake i did. Can any one help me out. This is my code.
IndexController.php
public function indexAction()
{
$mail = new Zend_Mail();
$mail->addTo('chaitanya5a2#gmail.com', 'Chaitanya Kanuri')
->setFrom('chaitanya#gmail.com', 'Myself')
->setSubject('My Subject')
->setBodyText('Email Body')
->send();
}
Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDefaultEmailTransport() {
$emailConfig = $this->getOption('email');
$smtpHost = $emailConfig['transportOptionsSmtp']['host'];
unset($smtpHost);
$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $emailConfig['transportOptionsSmtp']);
Zend_Mail::setDefaultTransport($mailTransport);
}
}
application.ini
email.transportOptionsSmtp.host = "smtp.gmail.com"
email.transportOptionsSmtp.auth = "login"
email.transportOptionsSmtp.username = "mygmail#gmail.com"
email.transportOptionsSmtp.password = "mygmailpassword"
email.transportOptionsSmtp.ssl = "ssl"
email.transportOptionsSmtp.port = 465
Thanks In advance.
I can send email from my pc using swiftmailer, but mail not sending in server.
I'm using swiftmailer 5.0.1. Project details are,
A simple php project in netbeans
swiftmailer 5.0.1
twig 1.13.1
My code is
public function init() {
$this->username = 'username#gmail.com';
$this->password = 'password';
$this->host = 'ssl://smtp.gmail.com';
$this->port = 465;
$this->from = 'username#gmail.com';
$this->subject = 'Company - contact';
$this->body_part_type = 'text/html';
}
public function send_email($from_name_add, $to_add, $fullname, $email, $mobile, $content) {
$this->init();
$transport = Swift_SmtpTransport::newInstance($this->host, $this->port)
->setUsername($this->username)
->setPassword($this->password);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$cid = $message->embed(Swift_Image::fromPath('../public_html/pic/logo.png'));
$this->body = $this->renderEmailTemplate('email', $fullname, $email, $mobile, $content, $cid);
$message->setSubject($this->subject)
->setFrom(array('username#gmail.com' => '' . $from_name_add))
->setTo($to_add)
->setContentType($this->body_part_type)
->setBody($this->body);
$result = $mailer->send($message);
return $result;
}
This code works FINE in my pc. But after upload this code/project to server, mail not sending. Error is,
<br />
<b>Fatal error</b>: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host ssl://smtp.gmail.com [Connection timed out #110]' in /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php:259
Stack trace:
#0 /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php(64): Swift_Transport_StreamBuffer->_establishSocketConnection()
#1 /home/am***/lib/Swift/classes/Swift/Transport/AbstractSmtpTransport.php(115): Swift_Transport_StreamBuffer->initialize(Array)
#2 /home/am***/lib/Swift/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start()
#3 /home/am***/controller/send_mail.php(54): Swift_Mailer->send(Object(Swift_Message))
#4 /home/am***/public_html/contact.php(43): send_mail->send_email('Am*** Inc', 'fe****#gma...', 'asdf', 'asdf#in.com', '111111111111', 'Testing mail')
#5 {main}
thrown in <b>/home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php</b> on line <b>259</b><br />
HINT: There is an allready running php symfony2 project in that server, this project can send mail successfully.
Here is the symfony2 code,
$message = \Swift_Message::newInstance()
->setSubject($sub)->setFrom($from)->setTo($to)->setContentType("text/html")
->setBody($this->renderView('FZAm***Bundle:Layout:mail.html.twig', array
('name' => $this->fullname, 'mobile' => $this->mobile, 'email' => $this->email,
'content' => $this->content, 'time' => $this->sys_time, 'ip' => $userip,
'server_time' => date('Y-m-d H:i:s'))
));
try {
$this->get('mailer')->send($message);
// catch and other follows.
Config details are,
mail_contact_from: username#gmail.com
mail_contact_to: username#gmail.com
mail_contact_sub: Contact info
I passed only this details and all settings are default. If any info needed please ask i'l post.
Reason i'm changing from symfony2 project to this ordinary php+swift+twig is my hosting is only 100mb and i need to upload more images. But symfony2 occupy more space.
Looks like your live server is missing OpenSSL, so you need to enable it in order to get secure connections working (i.e. enable the php_openssl module). Also check this question.
After some search in google.
To send mail using gmail auth you need to use this code,
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465);
This is the correct way to send mail. This mail will be send by gmail.
PHP use mail() to send just a mail,
mail($to,$subject,$message,$headers);
This code sends a mail using php code.
Swiftmailer can also send a mail using this php mail() function,
Here is swift code.
$transport = Swift_MailTransport::newInstance();
// nothing inside ()
The problem in this mail is, gmail displays following message,
This message may not have been sent by: username#gmail.com
Sometimes this mail will go to spam.