I know how to use SMTP with PHPMailer:
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
And it works fine. But my question is:
How can I configure PHPMailer to use these settings on default, so that I do not have to specify them each time I want to send mail?
Create a function, and include / use it.
function create_phpmailer() {
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
return $mail;
}
And call create_phpmailer() to create a new PHPMailer object.
Or you can derive your own subclass, which sets the parameters:
class MyMailer extends PHPMailer {
public function __construct() {
parent::__construct();
$this->IsSMTP(); // telling the class to use SMTP
$this->SMTPAuth = true; // enable SMTP authentication
$this->Host = "mail.yourdomain.com"; // sets the SMTP server
$this->Username = "yourname#yourdomain"; // SMTP account username
$this->Password = "yourpassword"; // SMTP account password
}
}
and use new MyMailer().
Can I not just edit the class.phpmailer.php file?
It's best not to edit class files themselves because it makes the code harder to maintain.
You can also use this hook:
/**
* Fires after PHPMailer is initialized.
*
* #since 2.2.0
*
* #param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
*/
do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
From the source of the wp_mail function itself to modify the phpmailer class directly.
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;
}
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 have this script:
// Define SMTP Parameters
$params = array();
$params['host'] = 'mail.mydomain.com';
$params['port'] = '25';
$params['auth'] = 'true';
$params['username'] = 'valid#mydomain.com'; // this needs to be a legitimate mail account on the server and not an alias
$params['password'] = 'abcdef';
// Create the mail object using the Mail::factory method
include('Mail.php');
$mail_object =& Mail::factory('smtp', $params);
params['auth'] does not seem to work when set to 'true' but it does seem to work when set to 'PLAIN'. Oddly, the doc only states $params["auth"] - Whether or not to use SMTP authentication. Default is FALSE. which makes it sound like you can use FALSE vs. 'PLAIN'
The possible authentication methods are:
'DIGEST-MD5'
'CRAM-MD5'
'LOGIN'
'PLAIN'
or false for no authentication.
http://pear.github.io/Net_SMTP/#smtp-authentication
PS: You could have noticed, that pear/Mail package is used. By the way it is relative old with latest changes in 2010