Can't send mail with Gmail - php

I'm trying to send an email when a user is subscribing in my web site.
To save me time ... I'm using Swift_Mailer with Symfony.
First, I tried to send a mail with the console :
php .\bin\console swiftmailer:email:send
And that's working, the mail was sent and the client received it.
So now I said to myself, I will be able to send emails with the code.
That's my Controller code :
public function register(Request $request, \Swift_Mailer $mailer)
{
// Here saving new user in the database
$this->sendMail($user->getEMail(), $mailer);
$content = $this->renderView("register.html.twig");
return new Response($content);
}
private function sendMail($email, \Swift_Mailer $mailer)
{
$message = (new \Swift_Message('Hello Email'))
->setFrom(['my.email#gmail.com' => "my name"])
->setTo($email)
->setBody('Here is the message itself');
$mailer->send($message);
}
And That's my .env file :
MAILER_URL=gmail://my.email#gmail.com:myPasswordHere#localhost
When I'm trying to send the mail, no error, I tried this StackOverflow link, but no problem, echo "Successfull", but nothing in the Gmail send box and nothing my client email box.
Can you please help me to ... save me time ^^
------------------------------------------------------------- EDIT 1 ------------------------------------------------------------
I never edited the config/packages/swiftmailer.yaml file, that's it's content :
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
------------------------------------------------------------- EDIT 2 ------------------------------------------------------------
I also tryed to make a new transporter with this code :
$transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465))
->setUsername('my.email#gmail.com')
->setPassword('myPasswordHere');
$mailer = new \Swift_Mailer($transport);
And that's the error I get : Connection could not be established with host smtp.gmail.com [php_network_getaddresses: getaddrinfo failed: Unknown host. #0]
------------------------------------------------------------- EDIT 3 ------------------------------------------------------------
I've got a swiftmailer.yaml fil in the config/packages/dev folder and that's it's default content :
# See https://symfony.com/doc/current/email/dev_environment.html
swiftmailer:
# send all emails to a specific address
#delivery_addresses: ['me#example.com']
I tried to put the same content as in the config/packages/swiftmailer.yaml, but no result.

I don't see something like this in your code:
// Create the Transport
$transport = (new \Swift_SmtpTransport('mail hoster etc', port))
->setUsername('your email')
->setPassword('your password');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
Maybe it's a reason why your mails isn't sent.

Related

Why can't I send the mail from the form with symfony?

I am building this website and on one of the pages I have a contact form from which the user should be able to send a message to us.
.env :
###> symfony/google-mailer ###
# Gmail SHOULD NOT be used on production, use it in development only.
MAILER_DSN=gmail://myEmail.com:myPassword#default?verify_peer=0
###< symfony/google-mailer ###
mailer.yaml :
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
the code that is supposed to send the mail :
/**
* #Route("/contact", name="api_mail")
*/
public function mailAPI(Request $request, MailerInterface $mailer)
{
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = $_POST["Name"];
$mail = $_POST["Mail"];
$game = $_POST["Game"];
$category = $_POST["Categ"];
$message = $_POST["Msg"];
$email = (new Email())
->from($mail)
->to('myEmail#gmail.com')
->subject('Testing the mail sender from symfony.')
->text($message)
->html('<p> This is a message </p>');
$mailer->send($email);
}
return $this->render('default/index.html.twig', [
'controller_name' => 'DefaultController',
]);
}
}
At first I used mailCatcher and it caught the mails, now I configured the gmail thingy to send the mails via the gmail transport but it doesn't do anything.

how can i use smtp config thats received from form?

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

Laravel 5.4 SMTP emails not working

I am using laravel 5.4 and configured gmail smtp details for sending emails. Below is code and return expection error.
Email Code:
try {
Mail::raw('Text', function ($message) {
$message->to('lpkapil#mailinator.com');
});
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
print_r($e->getCode());
echo "</pre>";
die();
}
Returned Execption Message & Error code
Error Message:
Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
Error Code:
530
Gmail smtp details used:
MAIL_HOST: smtp.gmail.com
MAIL_PORT: 587
MAIL_ENCRYPTION: tls
username: gmail id
password: password
Please suggest a solution.
This is a easy way to send mails using Laravel.You can use this function on your controller. You have to make a blade template file as example "emailfile.blade.php" with what ever the details you want to show on the email and pass the variables to that blade using the inputs array as I mentioned below.
$inputs = array(
'name'=> 'Your Name',
'address' =>'Your Address',
'company' =>'Your Company',
);
Mail::send('emailfile', $inputs, function ($message) {
$message->from('sender#gmail.com', 'Sender Name');
$message->to('reciver#gmail.com',$name=null)->subject('Mail Subject!');
$message->cc('cc#gmail.com');
});

Email is not Receiving through Swift Mailer Symfony2

i tried to send email through swiftmailer
response code 200 ok but still no email recived.
controller code
public function EmaiAction(Request $request)
{
$mailer = $this->get('mailer');
$logger = new \Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
$message = \Swift_Message::newInstance()
->setSubject('Hello')
->setFrom('mohd#abc.com')
->setTo('***#gmail.com')
->setBody('This is a test email.');
if ($this->get('mailer')->send($message)) {
echo '[SWIFTMAILER] sent email to ';
} else {
echo '[SWIFTMAILER] not sending email: ' . $mailer->dump();
}
die("email send");
}
output
[SWIFTMAILER] sent email to
config.yml
swiftmailer:
disable_delivery: true
transport: smtp
encryption: ssl
port: 465
auth_mode: login
host: smtp.gmail.com
username: ***#gmail.com
password: passwrd
delivery_address: abc#gmail.com
on doing echo in if/else its going in if condition that means its true.
so why im not recieving emails.
no error logs appears while sending an emails
im using cpanel app is production enviornment.
disable_delivery: true
This disables mail sending for development (See Docs)
Additionally try the swiftmailer config like this
swiftmailer:
transport: gmail
username: ***#gmail.com
password: passwrd
$message = \Swift_Message::newInstance()
->setSubject('Hello')
->setFrom('mohd#abc.com')
->setTo('***#gmail.com')
->setBody('This is a test email.');
$this->get('mailer')->send($message);

Swiftmailer config : send mail using gmail

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.

Categories