I want to send email from localhost using SMTP mail in Yii Framework. I am already copying PhpMailer into extensions folder. I am following the tutorial to setting the main.php like below
'components'=>array(
'Smtpmail'=>array(
'class'=>'application.extensions.smtpmail.PHPMailer',
'Host'=>"smtp.gmail.com",
'Username'=>'myGmail#gmail.com',
'Password'=>'myPassword',
'Mailer'=>'smtp',
'Port'=>465,
'SMTPAuth'=>true,
'SMTPSecure' => 'ssl'
),
Then, in my controller :
$mail=Yii::app()->Smtpmail;
$mail->SetFrom('myGmail#gmail.com', 'My Name');
$mail->Subject= $subject;
$mail->MsgHTML($email);
$mail->AddAddress($to, "");
The browser give me an error :
The following From address failed: myGmail#gmail.com : Called Mail() without being connected.
What is wrong with that?
for smtp.gmail.com try using 587 for port and tls for SMTPsecure
'Smtpmail'=>array(
'class'=>'application.extensions.smtpmail.PHPMailer',
'Host'=>"smtp.gmail.com",
'Username'=>'myGmail#gmail.com',
'Password'=>'myPassword',
'Mailer'=>'smtp',
'Port'=>'587', // or 587
//'SMTPAuth'=>true,
'SMTPAuth'=>false,
'SMTPSecure' => 'tls'
),
,
Related
I've been trying to send an email programmatically from the server using SimpleEmail. I use Kotlin. So far it always leads to an error that seems to only use port 465 despite setting it to a different port. I've been trying to find out why it does this but I have not seen any point this out.
SimpleEmail().apply {
hostName = "smtp.gmail.com"
setSmtpPort(587)
setAuthenticator(DefaultAuthenticator("**email**", "**password**"))
setSSLOnConnect(true)
setFrom("**email**")
subject = "TEST"
setMsg("TEST")
addTo(email)
}.send()
The error:
org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
A little late, but maybe it still helps someone.
Ports 25 and 587 use TLS, while port 465 uses SSL. If you setSSLOnConnect, then it forces the port 465, because that is the SSL port.
Instead, you have to use setStartTLSEnabled and optionally setStartTLSRequired to true, but not setSSLOnConnect.
hostName should be = "smtp.googlemail.com" but not "smtp.gmail.com", if it does not work, check the gmail settings for access to smpt.
const val myEmail = "test#gmail.com"
const val myPassword = "test"
const val receivingAddress = "test"
fun main(args: Array<String>) {
SimpleEmail().apply {
hostName = "smtp.googlemail.com"
isSSLOnConnect = true
subject = ("subject")
setSmtpPort(465)
setAuthenticator(DefaultAuthenticator(myEmail, myPassword))
setFrom(myEmail)
setMsg("message")
addTo(receivingAddress)
}.send() // will throw email-exception if something is wrong
}
I am using Swift Mailer 406 for sending emails. I connect to my smtp.gmail.com account and then I do:
->setFrom(array($from => $fromname))
But the emails sent got the original gmail account email.
Can I change it?
gmail doesn't allow you to use random From addresses. You have to add and validate the address you'd like to use in the gmail settings:
Settings -> Accounts -> Send mail as -> Add another email address you own
$email=$entity->getEmail();
->setFrom(array('your fix adress#gmail.com' => $email))
In your Parameters.yml you should make this configuration:
parameters:
database_host: 127.0.0.1
database_port: null
database_name: your db name
database_user: root
database_password: null
mailer_transport: smtp
mailer_host: smtp.gmail.com
mailer_user: your fix adress#gmail.com
mailer_password: your password of your fix adress
mailer_port: 465
mailer_encryption: ssl
auth_mode: login
secret: 3556f3fb752a82ce0ee9c419ef793b7a707f324a
And in your contact controller you should add this to fix setfrom() function of swiftmailer:
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$subject = $entity->getSubject();
$name=$entity->getName();
$email=$entity->getEmail();
$body=$entity->getBody();
$message = \Swift_Message::newInstance('here')
->setSubject("Shoppify email from ".$name." Subject ".$subject)
->setFrom(array('your fix adress#gmail.com' => $email))
->setTo('your adress destionation#example.com')
->setBody($body);
$this->get('mailer')->send($message);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('email_sended'));
}
I've tried a bunch of alterations to my code but with no effect. The code itself does not return any errors but instead gives a success message. I am using gmail as my relay.
P.S, I commented out $mail->IsSMTP(); because I saw a similar question here that used it as a fix, I was getting an "smtp failed to connect" error.
I am using PHPmailer 6.0.
Here is my code:
<?php
require_once('vendor/autoload.php');
define('GUSER', 'example#gmail.com'); // GMail username
define('GPWD', '*********'); // GMail password
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer\PHPMailer\PHPMailer(true); // create a new object
//$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 4; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
smtpmailer('to#mail.com', 'from#mail.com', 'yourName', 'test mail message', 'Hello World!');
if (smtpmailer('to#mail.com', 'from#mail.com', 'yourName', 'test mail message', 'Hello World!')) {
// do something
}
if (!empty($error)) echo $error;
?>
If I uncomment $mail->IsSMTP(); I get this error log:
2017-12-27 07:58:54 Connection: opening to smtp.gmail.com:465, timeout=300, options=array()
2017-12-27 07:58:54 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:465 (Network is unreachable) [/srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/SMTP.php line 325]
2017-12-27 07:58:54 SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Fatal error: Uncaught PHPMailer\PHPMailer\Exception: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting in /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php:1726 Stack trace: #0 /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Wed, 27 D...', 'Hello World!\r\n') #1 /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend() #2 /srv/disk2/2564570/www/consorttest.dx.am/mailtest.php(23): PHPMailer\PHPMailer\PHPMailer->send() #3 /srv/disk2/2564570/www/consorttest.dx.am/mailtest.php(32): smtpmailer('to#mail.com', 'from#mail.com', 'yourName', 'test mail messa...', 'Hello World!') #4 {main} thrown in /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1726
You're not "using gmail as your relay" if you comment out isSMTP() because then it's not using SMTP at all, and will ignore all your SMTP settings. You're sending via your local mail server using PHP's built-in mail function.
When sending through gmail, you can't use arbitrary from addresses, though you can preset aliases in your gmail account.
You've based your code on a very old and obsolete example - use the gmail one provided with PHPMailer.
The most important part of the error output is: Network is unreachable - that probably means your ISP blocks outbound SMTP - are you by any chance using GoDaddy?
Next up, you have a basic misconfiguration: you're connecting to port 465 using SMTPSecure = 'tls', which means it will try to use SMTP+STARTTLS explicit TLS encryption, and that just won't work on port 465. This is a key reason to use the provided examples - they don't make basic errors like this.
Every one of these things is covered in the troubleshooting guide the error links to.
This is the issue what i am facing
Localhost
Test mail with SMTP settings work
New user creation mail using the above smtp settings work
Server
Test mail with SMTP settings work
New user creation mail using the above smtp settings doesn't work
I echoed the mail smtp settings in both the cases and they are exactly same. The error i am getting is
SMTP -> ERROR: Failed to connect to server: php_network_getaddresses:
getaddrinfo failed: Name or service not known (0)SMTP Connect()
failed.
Any suggestions would be helpful.
I further debug it. The behavior turns out to be wierd
if (isset($_POST['User']))
{
if (UserUtil::validateAndSaveUserData($model, $_POST))
{
$mailer = new UiMailer();
$mailer->setFrom('fromAddress', 'fromName');
$mailer->setTo('toaddress');
$mailer->setSubject('Test subject');
$mailer->setBody('Test Body');
$mailer->Mailer = 'smtp';
$mailer->Username = 'username';
$mailer->Password = 'password';
$mailer->Host = 'host';
$mailer->Port = 25;
$mailer->SMTPAuth = true;
$status = $mailer->send() ? true : false;
if($status == true)
{
print "Sucess";
}
else
{
print $mailer->ErrorInfo . "</br>";
print "Failuere";
}
exit;
}
}
If i comment the call if (UserUtil::validateAndSaveUserData($model, $_POST)), it works fine. In the function i am validating and saving models using Yii framework. I further debug the function. I have the following relation in the system
User has one person
User has one address
So in the above call, if i comment the address part which $model->address->attributes or $model->address->validate or $model->address->save(), it works fine. The save functionality for address works fine. There are no issues related to it.
after deploying I gettin this error below when i try to send an mail:
500 | Internal Server Error | Swift_TransportException
Connection could not be established with host smtp.gmail.com [Connection timed out #110]
stack trace
* at ()
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Transport/StreamBuffer.php line 235 ...
232. }
233. if (!$this->_stream = fsockopen($host, $this->_params['port'], $errno, $errstr, $timeout))
234. {
235. throw new Swift_TransportException(
236. 'Connection could not be established with host ' . $this->_params['host'] .
237. ' [' . $errstr . ' #' . $errno . ']'
238. );
* at Swift_Transport_StreamBuffer->_establishSocketConnection()
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Transport/StreamBuffer.php line 70 ...
67. break;
68. case self::TYPE_SOCKET:
69. default:
70. $this->_establishSocketConnection();
71. break;
72. }
73. }
* at Swift_Transport_StreamBuffer->initialize(array('protocol' => 'ssl', 'host' => 'smtp.gmail.com', 'port' => 465, 'timeout' => 30, 'blocking' => 1, 'type' => 1))
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Transport/AbstractSmtpTransport.php line 101 ...
98.
99. try
100. {
101. $this->_buffer->initialize($this->_getBufferParams());
102. }
103. catch (Swift_TransportException $e)
104. {
* at Swift_Transport_AbstractSmtpTransport->start()
in SF_ROOT_DIR/lib/vendor/symfony/lib/vendor/swiftmailer/classes/Swift/Mailer.php line 74 ...
71.
72. if (!$this->_transport->isStarted())
73. {
74. $this->_transport->start();
75. }
76.
77. return $this->_transport->send($message, $failedRecipients);
* at Swift_Mailer->send(object('Swift_Message'), array())
in SF_ROOT_DIR/lib/vendor/symfony/lib/mailer/sfMailer.class.php line 300 ...
297. return $this->realtimeTransport->send($message, $failedRecipients);
298. }
299.
300. return parent::send($message, $failedRecipients);
301. }
302.
303. /**
* at sfMailer->send(object('Swift_Message'))
in SF_ROOT_DIR/lib/vendor/symfony/lib/mailer/sfMailer.class.php line 263 ...
260. */
261. public function composeAndSend($from, $to, $subject, $body)
262. {
263. return $this->send($this->compose($from, $to, $subject, $body));
264. }
265.
266. /**
* at sfMailer->composeAndSend('tirengar#gmail.com', 'tirengarfio#hotmail.com', 'Confirm Registration', 'Hello fjklsdjf,<br/><br/> Click here to confirm your registration<br/><br/> Your login information can be found below:<br/><br/> Username: fjklsdjf<br/> Password: m')
in SF_ROOT_DIR/plugins/sfDoctrineGuardExtraPlugin/modules/sfGuardRegister/lib/BasesfGuardRegisterActions.class.php line 89 ...
86. $user->getEmailAddress(),
87. 'Confirm Registration',
88. $message
89. );
90. }
91.
92. /**
* at BasesfGuardRegisterActions->sendRegisterConfirmMail(object('sfGuardUser'), 'm')
in SF_ROOT_DIR/plugins/sfDoctrineGuardExtraPlugin/modules/sfGuardRegister/lib/BasesfGuard
This is my configuration in factories.yml.
all:
mailer:
param:
delivery_strategy: realtime
transport:
class: Swift_SmtpTransport
param:
host: smtp.gmail.com
port: 465
encryption: ssl
username: tirengarfio
password: XXXX
The port 465 is open the my remote host. No problem in localhost.
Any idea?
--
Javi
Ubuntu 8.04
I have taken these instructions directly from gmail site.
you have to use #gmail.com in your username.
Outgoing Mail (SMTP) Server - requires TLS: smtp.gmail.com (use authentication)
Use Authentication: Yes
Use STARTTLS: Yes (some clients call this SSL)
Port: 465 or 587
Account Name: your full email address (including #gmail.com)
Google Apps users, please enter username#your_domain.com
Password: your Gmail password
You need to open 465 on firewall
On CSF firewall you need to add 465 on TCP_OUT =
I don't know if this helps, buy I've run with the same problem on my local machine (Windows). For resolving this I had to copy two dlls on the php directory to system32(ssleay.dll and libeay.dll) and unncoment the extension php_openssl.dll on my apache configuration. There might be a similar solution for linux. I suggest you contact the hosting because it's quite possible that you cannot perform this solution on a shared hosting.
Well, I had the same problem for a while, replacing: smtp.gmail.com with 173.194.65.108 actually worked for me!
If you get this constantly without any luck, then check the settings again.
I was overlooking my settings and later found the host was wrong.
I used,
smtp.google.com
instead of
smtp.gmail.com
Too silly, but it happened to me.