I trying to send emails with Gmail using gmail api with xoauth authentication.
The IMAP example from google works fine.
I am trying to implement the thing based on these articles:
http://www.boxuk.com/blog/php-smtp-xoauth2-gmail/
http://www.chargenevier.com/2013/02/google-smtp-and-oauth2-authentication/
I get the following error when i try to send the email:
Fatal error: Uncaught exception 'Zend_Mail_Protocol_Exception' with message '5.5.2 Syntax error. e5sm17066681bkg.3 - gsmtp
I also tried the openssl method on the first article, after write in XOAUTH2 i get the same error from the server and connection is closed.
Interesting when i do echo base64_encode("user=\1auth=Bearer \1\1") i got a string whitch is more shorter than that when i echo the $smtpInitClientRequestEncoded variable what is generated with constructAuthString method, what is working fine in the IMAP example.
And mail.google.com gives 5.5.2 Cannot decode response for the shorter encoded string.
function constructAuthString($email, $accessToken) {
return base64_encode("user=$email\1auth=Bearer $accessToken\1\1");
}
function sendEmail($email,$accessToken){
$smtpInitClientRequestEncoded = constructAuthString($email, $accessToken);
echo '<br/><br/>BASE64: ' . $smtpInitClientRequestEncoded;
$config = array('ssl' => 'ssl',
'port' => '465',
'auth' => 'xoauth',
'xoauth_request' => $smtpInitClientRequestEncoded
);
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
$mail = new Zend_Mail();
$mail->setBodyText('some body text');
$mail->setFrom($email, 'Some Sender');
$mail->addTo("myemail#gmail.com", 'Some Recipient');
$mail->setSubject('Test sending by smtp');
$mail->send($transport);
}
What do you think, what is wrong? Why dont this authenticates?
$accesToken was bad. I passed $client->getAccessToken(), but you need just the access_token string from this string, not the whole.
Related
can you help me figure out a way to use the email class of CI4 to send an email with an HTML as the message?
in Codeigniter 3 it is simple and goes like this:
$email->message($this->load->view('html_page_to_send_from_view_folder',$data,true));
but in Codeigniter 4 I tried doing this:
$email->setMessage(echo view('html_page_to_send_from_view_folder',$data,true));
It gives out an error:
syntax error, unexpected echo(T_ECHO), expecting ')'
I also tried putting the view in a variable like so:
$echo_page = echo view('html_page_to_send_from_view_folder',$data,true);
$email->setMessage($echo_page);
but it just throws the same error, I was searching all over the internet and the documentation but couldn't find a way to do this. Help please.
I tried this but got no error, and also got no email :'(
$echo_page = view('html_page_to_send_from_view_folder',$data,true);
$email->setMessage($echo_page);
According to this, if you want to use some template as your message body, you should do something like this:
// Using a custom template
$template = view("email-template", []);
$email->setMessage($template);
CodeIgniter 4 documentation states:
setMessage($body)
Parameters: $body (string) – E-mail message body
Returns: CodeIgniter\Email\Email instance (method chaining)
Return type: CodeIgniter\Email\Email
Sets the e-mail message body:
$email->setMessage('This is my message');
Okay I got it now I made it work by adding this code $email->setNewLine("\r\n"); at the end just after the setMessage:
$email->setMessage($my_message);
$email->setNewLine("\r\n");
and also I set the SMTP port 587 instead of 465:
$config['SMTPPort']= 587;
ALSO, for the setMessage, I did it like this:
$my_message = view('html_page_to_send_from_view_folder',["id" => $data['id']]);
$email->setMessage($my_message);
really weird man....
A. Firstly,
Instead of:❌
$echo_page = echo view('html_page_to_send_from_view_folder',$data,true);
Use this:✅
$echo_page = view('html_page_to_send_from_view_folder',$data);
Notice the luck of an echo statement and not passing true as the third argument of the view(...) hepler function.
B. Secondly, to submit HTML-based emails, ensure that you've set the mailType property to html. This can be achieved by using the setMailType() method on the Email instance. I.e:
$email->setMailType('html');
Alternatively, you could set the "mail type" by passing an array of preference values to the email initialize() method. I.e:
public function sendMail(): bool
{
$email = \Config\Services::email();
$email->initialize([
'SMTPHost' => 'smtp.mailtrap.io',
'SMTPPort' => 2525,
'SMTPUser' => '479d7c109ae335',
'SMTPPass' => '0u6f9d18ef3256',
'SMTPCrypto' => 'tls',
'protocol' => 'smtp',
'mailType' => 'html',
'mailPath' => '/usr/sbin/sendmail',
'SMTPAuth' => true,
'fromEmail' => 'from#example.com',
'fromName' => 'DEMO Company Name',
'subject' => 'First Email Test',
]);
$email->setTo('to#example.com');
$email->setMessage(view('blog_view'));
$response = $email->send();
$response ? log_message("error", "Email has been sent") : log_message("error", $email->printDebugger());
return $response;
}
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');
});
I am trying to send an email via Zend Mail Transport SMTP
I tried to browse sample codes and use it. What I have now is this code
$config = array('auth' => 'login',
'username' => 'sample#gmail.com',
'password' => 'samplepassword',
'port' => 587,
'ssl' => 'tls');;
$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
$mail = new Zend_Mail();
$mail->setBodyHtml('Hi From Dave.');
$mail->setFrom('noreply.networklabs#networklabs.com.ph');
$mail->addTo('john.decena#nokia.com', 'john.decena#nokia.com');
$mail->setSubject('Profile Activation');
$mail->send($transport);
Apparently, this code gives me error
Class 'User\Controller\Zend_Mail_Transport_Smtp' not found
May I know what I'm missing? because I tried to study their codes but they didn't have that error. And what credentials did I have to use.? Thanks in advance.
This really looks like a namespace problem.
I don't know which version of ZF2 you are using, but you need to add an use statement at the beginning of your file, something like
use Zend\Mail\Transport\Smtp;
and the create the new instance with
$transport = new Smtp('smtp.gmail.com', $config);
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.
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