I am stuck, constantly getting this error from PHPMailer:
"SMTP: Could not Authenticate"
I am using XOAuth2 of PHPMailer. I have tried dump and die on PHPMailer object, it shows the details configured correctly. I have matched refresh token, clientId and clientSecret but they are fine too.
My code is like this:
$phpMailer->SMTPAuth = true;
$phpMailer->SMTPSecure = 'tls';
$phpMailer->SMTPAutoTLS = false;
$phpMailer->Host = 'smtp.gmail.com';
$phpMailer->Port = 587;
$phpMailer->AuthType = 'XOAUTH2';
$path = base_path().'/Modules/Emails/credentials.json';
$credentials = json_decode(file_get_contents($path), true)['web'];
$phpMailer->setOAuth(
new OAuth(
[
'provider' => new Google(
[
'clientId' => $credentials['client_id'],
'clientSecret' => $credentials['client_secret'],
]
),
'clientId' => $credentials['client_id'],
'clientSecret' => $credentials['client_secret'],
'refreshToken' => $payload->refreshToken,
'userName' => $payload->from_email,
]
)
);
$phpMailer->setFrom($payload->from_email, "Haider Wain");
$phpMailer->addAddress('haiderwayne.9#gmail.com');
$phpMailer->Subject = 'Test phpmailer';
$phpMailer->CharSet = 'utf-8';
$phpMailer->msgHTML('hello test');
$phpMailer->AltBody = 'This email is HTML; enable HTML mail if you cannot see it.';
$true = $phpMailer->send();
dd($true);
I finally found the solution after 2 days. SMTP is only accepting full access "mail.google.com" for some reason. Any other scope given is rejected. After finding the solution I googled for why this is happening, and this guy explains a bit:
Using `gmail.send` scope with SMTP MSA
Related
I need to send mail to the admin with the inserted data using APi function ,
the function is look like that
public function requestbookingresort_post()
{
$languageid = $this->input->post('languageId');
$resort_id = $this->input->post('resortId');
$booking_from = $this->input->post('bookingFrom');
$booking_to = $this->input->post('bookingTo');
$contact_name = $this->input->post('contactName');
$contact_email = $this->input->post('contactEmail');
$contact_phone = $this->input->post('contactPhone');
$userid = $this->input->post('userId');
if (empty($languageid))
{
$languageRecord = getDefaultlanguage();
$languageid = $languageRecord->languageid;
}
$language_file = languagefilebyid($languageid);
$this->lang->load($language_file, $language_file);
if (empty($resort_id) || empty($booking_from) || empty($booking_to) || empty($contact_name) || empty($contact_email) || empty($contact_phone))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_in_booking');
$arr['data'] = array();
}
else
{
$dataArray = array(
"languageid" => $languageid,
"userid" => empty($userid) ? "0" : $userid,
"resortid" => $resort_id,
"bookingfrom" => date("Y-m-d", strtotime($booking_from)),
"bookingto" => date("Y-m-d", strtotime($booking_to)),
"contactname" => $contact_name,
"contactemail" => $contact_email,
"contactphone" => $contact_phone,
"requestdatetime" => date("Y-m-d H:i:s"),
);
$this->load->model("Resort_model");
$booking_id = $this->Resort_model->saveBookingRequest($dataArray);
if (empty($booking_id))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_occurred');
$arr['data'] = array();
}
else
{
$arr['status'] = 'success';
$arr['statusMessage'] = lang('booking_request_submit');
$arr['data'] = array();
}
}
$response = array(
"response" => $arr
);
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
But i'm new at codeigniter and didn't know how to get this passed data from the database to send mail with that to the admin mail or something ?
Try this.
public function requestbookingresort_post()
{
// Your operations
$response = array(
"response" => $arr
);
$this->sendMail($response)
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function sendMail($response)
{
$settings=$this->Some_model->getEmailSettings();
$mail = new PHPMailer();
$mail->IsSMTP(); // we are going to use SMTP
$mail->SMTPAuth = true; // enabled SMTP authentication
$mail->SMTPSecure = "ssl"; // prefix for secure protocol to connect to the server
$mail->Host = $settings->host; // setting GMail as our SMTP server
$mail->Port = $settings->port; // SMTP port to connect to GMail
$mail->Username = $settings->email; // user email address
$mail->Password = $settings->password; // password in GMail
$mail->SetFrom($settings->sent_email, $settings->sent_title); //Who is sending the email
$mail->AddReplyTo($settings->reply_email,$settings->reply_email); //email address that receives the response
$mail->Subject = "Your Booking has been confirmed";
$mail->IsHTML(true);
$body = $this->load->view('path/email_template', $response, true);
$mail->MsgHTML($body);
$destination = $response['contactEmail']; // Who is addressed the email to
$mail->AddAddress($destination);
if(!$mail->Send()) {
$data['code']=300;
$data["message"] = "Error: " . $mail->ErrorInfo;
}
}
Make sure you have PHPMailer in your libraries and you are loading the library in your constructor and I hope you are keeping Email settings in your database. If not you can manually provide host, port, username and password fields
I am trying to send email to multiple recipient address in cake php 3.
my codes are :
$this->loadModel('AsIndividualDetails');
$EmailDetails = $this-> AsIndividualDetails->find('all',['fields'=>'email']);
$EmailDetails = $EmailDetails->toArray();
foreach ($EmailDetails as $key => $a) {
$this->loadModel('DomainEmailDetails');
$DomainEmailDetails = $this-> DomainEmailDetails->find('all')->first();
$DomainEmailDetails = $DomainEmailDetails->toArray();
$host = 'ssl://'.$DomainEmailDetails['host_name'];
$username = $DomainEmailDetails['user_name'];
$password = $DomainEmailDetails['user_password'];
$port = $DomainEmailDetails['port'];
$email_to = $a['email'];
$senderName = 'abc';
$email_id ='xyz110#gmail.com';
Email::configTransport('WebMail', [
'className' => 'Smtp',
'host' => $host,
'port' => $port,
'timeout' => 30,
'username' => $username,
'password' => $password,
'client' => null,
'tls' => null,
]);
////////// SEND MAIL
$email = new Email('WebMail');
$email ->template('default','default')
->emailFormat('both')
->from([$username => $senderName])
->to($email_to)
->replyTo($email_id)
->subject('Client Message');
$response = $email->send('My msg');
if($response){
echo 'success';
}else{
echo 'failed';
}
}
When I run this script just only one mail send successfully and after that an error has come :
Cannot modify an existing config "WebMail"
How to solve this error and send mail to all recipient mail address.
If you really need set the config inside a loop, you could delete it before rewrite the config:
use Cake\Mailer\Email;
Email::dropTransport($key);
See Class Email API for more info
Make your email configuration outside of the loop. You don't want to try and establish the configuration every time you send the emails - just one time. Then send all the emails based on that one configuration.
I have a form that basically has 3 radio buttons that will let you pick a staff member you want to get in contact with. The form requires a name, email and message. I cannot find where it tells me what the error is. I have debugging on but do not know where the error is coming from.
My goal is to have it so that the person they select will be emailed and when the email is sent it will be redirected to a page that has the correct staff members info on it. However for the life of me I cannot get this to work. I believe everything works correct but when I inserted the code that I found on SO to connect to the SMTP servers and email the contact form input my formProcess.php breaks.
EDIT: With the help of some of you here I have found the solution to 2 of the errors I am getting. However now that I have fixed these errors I am getting a different error. I am now receiving this:
2015-12-23 04:42:59 SMTP ERROR: Failed to connect to server: Cannot allocate memory (12) 2015-12-23 04:42:59 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting 2015-12-23 04:42:59 SMTP ERROR: Failed to connect to server: Cannot allocate memory (12) 2015-12-23 04:42:59 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Warning: Cannot modify header information - headers already sent by (output started at /www/contact/phpmailer/class.smtp.php:234) in /www/contact/formProcess.php on line 80
EDIT 2: I have uploaded it to my hosted server. It has solved the error mentioned above. I now have an issue with the password failing, even though I have signed in using the password I am using in the code. Instead of copy/pasting the error message you can see it live on my site for yourself.
EDIT 3: I just noticed that there is an email from Gmail that says "Someone tried to sign in to your Google Account from an app that doesn't meet standard security standards." This can't be a coincidence can it? Is this why I cannot connect? and if so what can I do to meet security standards?
EDIT 4: I have now got everything working fine except for 2 things. 1, for some reason it is sending the emails twice. I am not sure why but I feel like I can figure it out. The real issue I am having now is that I now want to include Googles reCAPTCHA to my form as well. Everything works fine until I added this bit of code that I thought would verify if the reCAPTCHA was successful and if it wasn't just add an error to my code, but after I entered the code below to do that my code breaks.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'secret'=>'Well it says secret for a reason!',
'response'=> $_POST['g-recaptcha-response']
]
]);
$response = json_decode(curl_exec($curl));
if (!$response->success){
$errors[] = 'There was a problem with reCAPTCHA, please try again.';
};
And bellow is all code that processes the form.
<?php
session_start();
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once 'PHPMailerAutoload.php';
$errors = [];
$toWho ='';
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['who'])){
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message'],
'who' => $_POST['who']
];
foreach($fields as $field => $data) {
if(empty($data)) {
$errors[] ='The ' .$field. ' field is required.';
}
}
if ($fields['who'] == "staff1") {
$toWho = 'staff1#domain.com';
} else if ($fields['who'] == "staff2") {
$toWho = 'staff2#domain.com';
} else {
$toWho = 'staff3#domain.com';
}
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'secret'=>'Well it says secret for a reason!',
'response'=> $_POST['g-recaptcha-response']
]
]);
$response = json_decode(curl_exec($curl));
if (!$response->success){
$errors[] = 'There was a problem with reCAPTCHA, please try again.';
};
if(empty($errors)) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->smtpSecure = 'tls';
$mail->Port = 587;
// $mail->SMTPDebug = 3;
$mail->Host = 'mailen3.cloudsector.net';
$mail->From = "No-reply#domain.com";
$mail->Username = 'No-Reply#domain.com';
$mail->Password = 'PAsswoRD';
$mail->SetFrom("No-reply#domain.com", "No Reply" );
$mail->AddReplyTo($fields['email'], $fields['name']);
$mail->AddAddress($toWho, $fields['who']);
$mail->Subject = $fields['name'] . ' wants to talk!';
$mail->Body = 'From: ' .$fields['name']. ' (' .$fields['email']. ') ' .$fields['message']. ;
$mail->send();
if($mail->send()) {
header('Location: ../../' .$fields['who']. 'thanks.php');
die();
}else {
$errors[] = 'Sorry! Something went wrong and your message could not be sent. Please try again ';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: index.php');
?>
Try displaying errors by adding the following code at the top of your script:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
If you're getting a server error 500, Try commenting out small blocks of code until the script works. That way you can identify the problem.
Im trying to read mails from a gmail apps account by using Zend Framework. I've just transfered the Zend Framework dir to my server (path: /Zend/library/).
How do I load the Zend Framework and the Mail module? And how do I further read the mail?
I've tried the following with no results:
$path = 'Zend/library/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
I believe the syntax for reading the inbox is something like:
$mail = new Zend_Mail_Storage_Imap(array('host' => 'imap.gmail.com', 'user' => "name#domain.com", 'password' => "mypassword", 'ssl' => 'SSL'));
EDIT
The following code works:
$path = 'Zend/library/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
$mail = new Zend_Mail_Storage_Imap(array('host' => 'imap.gmail.com',
'user' => 'mail#domain.com',
'password' => 'password',
'ssl' => 'SSL'));
echo $mail->countMessages();`
... but when i try to echo unread emails:
echo "Unread mails:\n";
foreach ($mail as $message) {
if ($message->hasFlag(Zend_Mail_Storage::FLAG_SEEN)) {
continue;
}
// mark recent/new mails
if ($message->hasFlag(Zend_Mail_Storage::FLAG_RECENT)) {
echo '! ';
} else {
echo ' ';
}
echo $message->subject . "\n";
}
I get the following message:
Fatal error: Uncaught exception 'Zend_Mail_Storage_Exception' with message 'cannot login, user or password wrong' in /var/www/zvinx.dk/test/Zend/library/Zend/Mail/Storage/Imap.php:279 Stack trace: #0 /var/www/zvinx.dk/test/gmail.php(11): Zend_Mail_Storage_Imap->__construct(Array) #1 {main} thrown in /var/www/zvinx.dk/test/Zend/library/Zend/Mail/Storage/Imap.php on line 279
It says the username or password is wrong, which is weird cause I didnt change it from when it was working... How come this error occur?
the gmail settings are a little tricky. try:
$mail = new Zend_Mail_Storage_Imap(array('host' => 'imap.gmail.com',
'user' => 'mail#domain.com',
'port' => '993',
'password' => 'password',
'ssl' => 'tls',
'auth' => 'login'
));
NOTE: the gmail are using the SSL/TLS protocol which apparently is different than the standard SSL.
You really don't think that you can start using Zend Framework without reading/learning about the basics of the framework? At least take a look at the quickstart on how to use the framework with the autoloading features and then dive into the Zend_Mail documentation, more specifically the part that says "Reading Mail Messages"
There are the login setting i use to read emails via IMAP and dump attached files
public function imapAction()
{
$config = array('host'=> 'imap.gmail.com',
'user' => 'xx',
'password' => 'xx',
'ssl' => 'SSL',
'port' => 993);//995 pop, imap 993
$mail = new Zend_Mail_Storage_Imap($config);
$maxMessage = $mail->countMessages();
$this->logger->info($maxMessage);
for ($i = $maxMessage; $i <= $maxMessage; $i++)
{
$message = $mail->getMessage($i);
$this->logger->info($i.'Mail from '.$message->from.':'.$message->subject);
if($message->isMultipart())
{
$this->logger->info("has attachments");
$part = $message->getPart(2);
$cnt_typ = explode(";" , $part->contentType);
$name = explode("=",$cnt_typ[1]);
$filename = $name[1];//It is the file name of the attachement in browser
//This for avoiding " from the file name when sent from yahoomail
$filename = str_replace('"'," ",$filename);
$this->logger->info($filename);
$attachment = base64_decode($part->getContent());
$fhandle = fopen($filename, 'w');
fwrite($fhandle, $attachment);
fclose($fhandle);
}
}
}
I had the same issue and this instruction has helped me.
Quit all mail clients that are accessing the affected Gmail account. This means the Mail app on the iPhone and any other place you are accessing your Gmail from such as a computer.
Open browser and navigate to this page: http://www.google.com/accounts/DisplayUnlockCaptcha
Enter your full Gmail address, password and type the characters you see in the picture. Touch the unlock button to verify your account.
Try to read mails from a gmail apps account by using Zend Framework. Your Gmail access should be restored.
If you encounter this error and you are 100% sure about the password you provided it might come from the 2 factor authentication you set on your google account.
Google help gives indications on what to do in this case. I manage to get access to my account by generating an AppPassword in my case
$config = array('auth' => 'login',
'username' => '****#gmail.com',
'password' => '****',
'port' => '25',
'ssl' => 'tls');
$transport = new Zend_Mail_Transport_Smtp('smtp.googlemail.com', $config);
what should i do after that, where can i put the body and the recipient address.
Its described in the manual of Zendframework
Zend_Mail::setDefaultTransport($transport);
Then somewhere else instanciate Zend_Mail, write your mail and send it.
See the documentation for full examples (although the Zend docs admittedly often aren't great).
Based on a comment here:
$mail = new Zend_Mail();
$tr = new Zend_Mail_Transport_Smtp(...);
$mail->setFrom('...', 'Server');
$mail->addTo($to, '....');
$mail->setSubject($subject);
$mail->send();
Zend_Mail::setDefaultTransport($tr);
$mail->setBodyText($body);
Your example shows an empty link so it wont display anything.
Unless this is a modified example you used to post on here?
Does the following display anything when you run it, if not what do you get.
$smtpHost = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
$mail = new Zend_Mail();
$mail->setBodyText($form->getValue('body'));
$mail->setBodyHtml('my link');
$mail->setFrom($certtime['email'], $certtime['first_name'] . $certtime['last_name']);
$mail->addTo($form->getValue('reciever'));
$mail->setSubject('My Certificate');
$mail->send($smtpHost);