I'm attempting to use PHPMailer to set up my email to receive emails/messages via a contact form on my website. I'm having trouble setting it up. Submitting the contact form calls this php file sendemail.php:
<?php
require_once('phpmailer/PHPMailerAutoload.php');
$toemails = array();
$toemails[] = array(
'email' => 'myRealEmail#yahoo.com', // Your Email Address
'name' => 'My Name' // Your Name
);
// Form Processing Messages
$message_success = 'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.';
// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = 'your-recaptcha-secret-key'; // Your reCaptcha Secret
$mail = new PHPMailer();
// If you intend you use SMTP, add your SMTP Code after this Line
$mail->IsSMTP();
$mail->Host = "mail.yourdomain.com";
$mail->SMTPDebug = 3;
// $mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Port = 26;
$mail->Username = "yourname#yourdomain.com";
$mail->Password = "yourpassword";
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( $_POST['template-contactform-email'] != '' ) {
$name = isset( $_POST['template-contactform-name'] ) ? $_POST['template-contactform-name'] : '';
$email = isset( $_POST['template-contactform-email'] ) ? $_POST['template-contactform-email'] : '';
$phone = isset( $_POST['template-contactform-phone'] ) ? $_POST['template-contactform-phone'] : '';
$service = isset( $_POST['template-contactform-service'] ) ? $_POST['template-contactform-service'] : '';
$subject = isset( $_POST['template-contactform-subject'] ) ? $_POST['template-contactform-subject'] : '';
$message = isset( $_POST['template-contactform-message'] ) ? $_POST['template-contactform-message'] : '';
$subject = isset($subject) ? $subject : 'New Message From Contact Form';
$botcheck = $_POST['template-contactform-botcheck'];
if( $botcheck == '' ) {
$mail->SetFrom( $email , $name );
$mail->AddReplyTo( $email , $name );
foreach( $toemails as $toemail ) {
$mail->AddAddress( $toemail['email'] , $toemail['name'] );
}
$mail->Subject = $subject;
$name = isset($name) ? "Name: $name<br><br>" : '';
$email = isset($email) ? "Email: $email<br><br>" : '';
$phone = isset($phone) ? "Phone: $phone<br><br>" : '';
$service = isset($service) ? "Service: $service<br><br>" : '';
$message = isset($message) ? "Message: $message<br><br>" : '';
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = "$name $email $phone $service $message $referrer";
// Runs only when File Field is present in the Contact Form
if ( isset( $_FILES['template-contactform-file'] ) && $_FILES['template-contactform-file']['error'] == UPLOAD_ERR_OK ) {
$mail->IsHTML(true);
$mail->AddAttachment( $_FILES['template-contactform-file']['tmp_name'], $_FILES['template-contactform-file']['name'] );
}
// Runs only when reCaptcha is present in the Contact Form
if( isset( $_POST['g-recaptcha-response'] ) ) {
$recaptcha_response = $_POST['g-recaptcha-response'];
$response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response );
$g_response = json_decode( $response );
if ( $g_response->success !== true ) {
echo '{ "alert": "error", "message": "Captcha not Validated! Please Try Again." }';
die;
}
}
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
echo '{ "alert": "success", "message": "' . $message_success . '" }';
else:
echo '{ "alert": "error", "message": "Email <strong>could not</strong> be sent due to some Unexpected Error. Please Try Again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '" }';
endif;
} else {
echo '{ "alert": "error", "message": "Bot <strong>Detected</strong>.! Clean yourself Botster.!" }';
}
} else {
echo '{ "alert": "error", "message": "Please <strong>Fill up</strong> all the Fields and Try Again." }';
}
} else {
echo '{ "alert": "error", "message": "An <strong>unexpected error</strong> occured. Please Try Again later." }';
}
?>
Which calls this PHPMailerAutoload.php file:
<?php
/**
* PHPMailer SPL autoloader.
* PHP Version 5
* #package PHPMailer
* #link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* #author Marcus Bointon (Synchro/coolbru) <phpmailer#synchromedia.co.uk>
* #author Jim Jagielski (jimjag) <jimjag#gmail.com>
* #author Andy Prevost (codeworxtech) <codeworxtech#users.sourceforge.net>
* #author Brent R. Matzelle (original founder)
* #copyright 2012 - 2014 Marcus Bointon
* #copyright 2010 - 2012 Jim Jagielski
* #copyright 2004 - 2009 Andy Prevost
* #license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* #note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer SPL autoloader.
* #param string $classname The name of the class to load
*/
function PHPMailerAutoload($classname)
{
//Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
if (is_readable($filename)) {
require $filename;
}
}
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
//SPL autoloading was introduced in PHP 5.1.2
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register('PHPMailerAutoload', true, true);
} else {
spl_autoload_register('PHPMailerAutoload');
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* #param string $classname The name of the class to load
*/
function __autoload($classname)
{
PHPMailerAutoload($classname);
}
}
As you can see in the initial php file it was using 'mail()' which I switched to be SMTP now. However, I've never used this and am very confused on how to use it. As you can see from the template, Host has: mail.yourdomain.com -- Is that my website domain, my email service providers domain? Next it asks for a Username and Password. Where do I find those? What are they the User/Pass for? I'm just trying to set this up for my regular email address, not one generated by cPanel or something like that. Thanks for the help.
I've done a few things now like pinging yahoo and my domain's server to get the address, I think I got that? But not entirely sure which is the correct one. I know the port should be like 587 too I think. For Yahoo, I pinged their server or whatever via console so would the following be what I fill in:
Host = "mta7.am0.yahoodns.net"
// Host = "smtp.mail.yahoo.com"
Username = "myYahooEmail#yahoo.com"
Password = "myYahooPassword"
I tried the above and I still get this:
Email could not be sent due to some Unexpected Error. Please Try Again
later.
Reason: SMTP connect() failed.
Another question along the same line is if this is your Password for your email account, what happens if you have 2step Authentication or something like that? Yahoo (the email I'd like to send messages to. I have GMail as well, but ignoring that for now) doesn't actually even let me sign in with my Password anymore. They send me a text w/ a code every time someone tries to log in on my account.
Edit:
TRied this code already via the link posted in the comment below. I suppose I might have implemented it wrong?:
$mail->IsSMTP();
$mail->Host = "smtp.mail.yahoo.com";
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
// $mail->SMTPSecure = 'ssl';
$mail->Username = "---#yahoo.com";
$mail->Password = "---";
Via Synchro's comments, I added: $mail->SMTPSecure = 'tls'; instead and that made my contact form never submit (just keeps spinning like it wants to send the message).
Related
I'm having issues with Google reCapcha verification in a form using PHPmailer. When the form is completed and the check in "I'm not a robot" is ok, press SEND and this message appears:
"reCaptcha is not Valid! Please try again.".
I've tried with reloading, change navigator to latest version, delete historial, and nothing works.
This is the message in the Google reCapcha admin panel: "We have detected that your website does not verify reCAPTCHA solutions. These verifications are necessary for the service to function properly on your website. You can get more information on our developer website".
Furthermore, I've set the allow_url_fopen = on for testing, but still doesn't work.
Does anyone figure out what's going on, and what's the best solution?
Actualization 13/06:
The ERROR_LOG shows this:
[13-Jun-2021 21:20:22 UTC] PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mywebsite/public_html/include/contact-form.php on line 90
[13-Jun-2021 21:20:22 UTC] PHP Warning: file_get_contents(https://www.google.com/recaptcha/api/siteverify?secret=XX--very long code here--XX): failed to open stream: no suitable wrapper could be found in /home/mywebsite/public_html/include/contact-form.php on line 90
The contact-form.PHP file original is this:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/src/Exception.php';
require 'php-mailer/src/PHPMailer.php';
//require 'php-mailer/src/SMTP.php';
// Enter your email address. If you need multiple email recipes simply add a comma: email#domain.com, email2#domain.com
$to = "";
// Add your reCaptcha Secret key if you wish to activate google reCaptcha security
$recaptcha_secret_key = '';
// Default message responses
const RESPONSE_MSG = [
'success' => [
"message_sent" => "We have <strong>successfully</strong> received your message. We will get back to you as soon as possible."
],
'form' => [
"recipient_email" => "Message not sent! The recipient email address is missing in the config file.",
"name" => "Contact Form",
"subject" => "New Message From Contact Form"
],
'google' => [
"recapthca_invalid" => "reCaptcha is not Valid! Please try again.",
"recaptcha_secret_key" => "Google reCaptcha secret key is missing in config file!"
]
];
//This functionality will process post fields without worrying to define them on your html template for your customzied form.
//Note: autofields will process only post fields that starts with name widget-contact-form OR with custom prefix field name
$form_prefix = isset($_POST["form-prefix"]) ? $_POST["form-prefix"] : "widget-contact-form-";
$form_title = isset($_POST["form-name"]) ? $_POST["form-name"] : RESPONSE_MSG['form']['name'];
$subject = isset($_POST[$form_prefix."subject"]) ? $_POST[$form_prefix."subject"] : RESPONSE_MSG['form']['subject'];
$email = isset($_POST[$form_prefix."email"]) ? $_POST[$form_prefix."email"] : null;
$name = isset($_POST[$form_prefix."name"]) ? $_POST[$form_prefix."name"] : null;
if( $_SERVER['REQUEST_METHOD'] == 'POST') {
if($email != '') {
if(empty($to)) {
$response = array ('response'=>'warning', 'message'=> RESPONSE_MSG['form']['recipient_email']);
echo json_encode($response);
die;
}
//If you don't receive the email, enable and configure these parameters below:
//$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
//$mail->IsSMTP();
//$mail->Host = 'mail.yourserver.com'; // Specify main and backup SMTP servers, example: smtp1.example.com;smtp2.example.com
//$mail->SMTPAuth = true;
//$mail->Port = 587; // TCP port to connect to 587 or 465
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
//$mail->Username = 'SMTP username'; // SMTP username
//$mail->Password = 'SMTP password'; // SMTP password
$mail = new PHPMailer;
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
if(strpos($to, ',') !== false){
$email_addresses = explode(',', $to);
foreach($email_addresses as $email_address) {
$mail->AddAddress(trim($email_address));
}
}
else {$mail->AddAddress($to);}
$mail->AddReplyTo($email, $name);
$mail->Subject = $subject;
// Check if google captch is present
if(isset($_POST['g-recaptcha-response'])) {
if(empty($recaptcha_secret_key)) {
$response = array ('response'=>'error', 'message'=> RESPONSE_MSG['google']['recaptcha_secret_key']);
echo json_encode($response);
die;
}
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$recaptcha_secret_key.'&response='.$_POST['g-recaptcha-response']);
$response_data = json_decode($response);
if ($response_data->success !== true ) {
$response = array ('response'=>'error', 'message'=> RESPONSE_MSG['google']['recapthca_invalid']);
echo json_encode($response);
die;
}
}
//Remove unused fields
foreach (array("form-prefix", "subject", "g-recaptcha") as $fld) {
unset($_POST[$form_prefix . $fld]);
}
unset($_POST['g-recaptcha-response']);
//Format eMail Template
$mail_template = '<table width="100%" cellspacing="40" cellpadding="0" bgcolor="#F5F5F5"><tbody><tr><td>';
$mail_template .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#F5F5F5" style="border-spacing:0;font-family:sans-serif;color:#475159;margin:0 auto;width:100%;max-width:70%"><tbody>';
$mail_template .= '<tr><td style="padding-top:20px;padding-left:0px;padding-right:0px;width:100%;text-align:right; font-size:12px;line-height:22px">This email is sent from '.$_SERVER['HTTP_HOST'].'</td></tr>';
$mail_template .= '</tbody></table>';
$mail_template .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#F5F5F5" style="padding: 50px; border-spacing:0;font-family:sans-serif;color:#475159;margin:0 auto;width:100%;max-width:70%; background-color:#ffffff;"><tbody>';
$mail_template .= '<tr><td style="font-weight:bold;font-family:Arial,sans-serif;font-size:36px;line-height:42px">'.$form_title.'</td></tr>';
$mail_template .= '<tr><td style="padding-top:25px;padding-bottom:40px; font-size:16px;">';
foreach ($_POST as $field => $value) {
$split_field_name = str_replace($form_prefix, '', $field);
$ucwords_field_name = ucfirst(str_replace('-', ' ', $split_field_name));
$mail_template .= '<p style="display:block;margin-bottom:10px;"><strong>'.$ucwords_field_name.': </strong>'.$value.'</p>';
}
$mail_template .= '</td></tr>';
$mail_template .= '<tr><td style="padding-top:16px;font-size:12px;line-height:24px;color:#767676; border-top:1px solid #f5f7f8;">Date: '.date("F j, Y, g:i a").'</td></tr>';
$mail_template .= '<tr><td style="font-size:12px;line-height:24px;color:#767676">From: '.$email.'</td></tr>';
$mail_template .= '</tbody></table>';
$mail_template .= '</td></tr></tbody></table>';
$mail->Body = $mail_template;
// Check if any file is attached
$attachments = [];
if (!empty($_FILES[$form_prefix.'attachment'])) {
$result = array();
foreach ($_FILES[$form_prefix.'attachment'] as $key => $value) {
for ($i = 0; $i < count($value); $i++) {
$result[$i][$key] = $value[$i];
}
}
foreach ( $result as $key => $attachment) {
$mail->addAttachment($attachment['tmp_name'],$attachment['name']);
}
}
if(!$mail->Send()) {
$response = array ('response'=>'error', 'message'=> $mail->ErrorInfo);
}else {
$response = array ('response'=>'success', 'message'=> RESPONSE_MSG['success']['message_sent']);
}
echo json_encode($response);
} else {
$response = array ('response'=>'error');
echo json_encode($response);
}
}
?>
Thank you,
Alejandra
I'm using Zapier to collect leads from facebook,and than send them to my CRM.
I Have a script connected to my CRM,that is supposed to handle the leads.
for every new lead the script will trigger,
the script collects the data passed from Zapier and converts it to an XML and sends it my client.
Everything works except for one thing.
The PHPMailer seems to cause trouble with zapier,because whenever the email() function is enabled Zapier will give me an Error.
FYI - this works when I go to the script url and set the GET parameters by hand .
the xml is being sent. But when triggering the script from zapier the problem occurs.
Zapier Error:
"We had trouble sending your test through.
The app returned "Internal Server Error" with no further details. It looks like the server for your connected app is down or currently experiencing problems. Please check the app's status page or contact support if there are no reported issues."
<?php
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
$lastName = isset($_GET['lastName']) ? $_GET['lastName'] : '';
$fullName = isset($_GET['fullName']) ? $_GET['fullName'] : '';
$phone = isset($_GET['phone']) ? $_GET['phone'] : '';
$experience = isset($_GET['experience']) ? $_GET['experience'] : '';
$city = isset($_GET['city']) ? $_GET['city'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
$utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : '';
$campaignId = isset($_GET['campaignId']) ? $_GET['campaignId'] : '';
$utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : '';
require 'vendor/autoload.php';
header('Content-Type: text/plain');
function createXML($data,$dataSource){
$dom = new DOMDocument('1.0', 'utf-8');
$cv = $dom->createElement("cv");
$candidate = $dom->createElement('candidate');
$source_type = $dom->createElement('source_type');
function recursive($dom, $parent, $key, $value) {
if(is_array($value)) {
$new_parent = $dom->createElement($key);
foreach($value as $k => $v){
recursive($dom, $new_parent, $k, $v);
}
$parent->appendChild($new_parent);
} else {
$field = $dom->createElement($key, htmlspecialchars($value));
$parent->appendChild($field);
}
}
foreach($dataSource as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $source_type, $key, $value);
}
foreach($data as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $candidate, $key, $value);
}
// $cv->appendChild($candidate)
$cv->appendChild($candidate);
$cv->appendChild($source_type);
$dom->appendChild($cv);
$node = $cv->appendChild($source_type);
$node->setAttribute('type','other');
$dom->formatOutput = true;
return $dom;
}
$data = array(
"first_name" => filter_var($firstName, FILTER_SANITIZE_STRING),
"last_name" => filter_var($lastName, FILTER_SANITIZE_STRING),
"mobile" => filter_var($phone, FILTER_SANITIZE_STRING),
'email' => '',
'id' => '',
);
$dataSource = array(
"source_title" => filter_var($utm_source, FILTER_SANITIZE_STRING),
"first_name" => '',
"last_name" => '',
"mobile" => '',
"email" => '',
"employee_number" => '',
"department" => '',
"email" => '',
);
//problematic function
function email(){
global $xmlData;
$mail = new PHPMailer(true);
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - " . $today;
}
///////// IF I uncomment bellow,Zapier will give me the following error:
//We had trouble sending your test through.
//The app returned "Internal Server Error" with no further details.
//It looks like the server for your connected app is down or currently experiencing problems.
//Please check the app's status page or contact support if there are no reported issues.
//Uncomment bellow.
// email();
?>
I Expect for every Lead to send an email containing a XML.
Two key problems. Firstly, you're using SMTP, but you have not set Host to your mail server - so it won't work unless it's localhost - is that the case?
You're asking PHPMailer to throw exceptions (by passing true to the constructor), but you don't have a try/catch block wrapped around the calls to PHPMailer, so any errors will result in uncaught exceptions - which will give you exactly the symptom you're seeing. Try this:
function email()
{
global $xmlData;
$mail = new PHPMailer(true);
try {
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - ".$today;
} catch (Exception $e) {
echo 'Sending failed'.$e->getMessage();
}
}
Overall, the main thing is to debug one thing at a time - check that the email() function actually works independently before you start trying to do things that depend on it working, because otherwise you won't know which bit of the code is failing.
If you're using PHP 7.0 or later, you can simplify those initial checks for params by using the null coalesce operator. You can replace this:
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
with:
$firstName = $_GET['firstName'] ?? '';
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
guys i have using a script to send mails, all seems fine with it and even i get the success message but sadly the emails are not delivered.. can any body look for any lapses in this code
Code
$body = "This is testmail please ignore";
$mail = new Zend_Mail ();
$tr = new Zend_Mail_Transport_Sendmail ( '-f' . $sentFromEmail );
Zend_Mail::setDefaultTransport ( $tr );
$mail->setReturnPath("user#admin.com");
$mail->setFrom ( "user#admin.com", 'Reporters' );
$mail->setBodyHtml ( $body );
$mail->addTo ( "samjam#gmail.com" );
$mail->setSubject ( "Weekly Report" );
try {
$mail->send ();
echo "Success";
} catch ( Exception $e ) {
echo "Mail sending failed.\n";
}
SMTP configuration
if (isset($config['ssl'])) {
switch (strtolower($config['ssl'])) {
case 'tls':
$this->_secure = 'tls';
break;
case 'ssl':
$this->_transport = 'ssl';
$this->_secure = 'ssl';
if ($port == null) {
$port = 465;
}
break;
}
}
if ($port == null) {
if (($port = ini_get('smtp_port')) == '') {
$port = 25;
}
}
The answer is that samjam#gmail.com is not an email address of any email account that you have access to.
It belongs to a private individual who you do not know.
This is the correct answer.
I would like to send data with UrlFetchApp but something is not working. I not understand where is the problem are not very experienced in question, can someone explain to me how to configure both files to send and receive parameters?
Google Apps Script:
function sendEXTmail(name,email,subject,body) {
var url = "http://www.mysite.com/willy.php";
var options = {
"method": "post",
"payload": {
"From_Name": "Fix Name",
"From_Email": "fix_mail#domain.com",
"To_Name": name,
"To_Email": email,
"Subject": subject,
"Message": body
}
};
var response = UrlFetchApp.fetch(url, options);
return response;
}
PHP:
require "phpmailer/class.phpmailer.php";
$from_name = (isset($_POST['From_Name'])) ? $_POST['From_Name'] : '';
$from_email = (isset($_POST['From_Email'])) ? $_POST['From_Email'] : '';
$to_name = (isset($_POST['To_Name'])) ? $_POST['To_Name'] : '';
$to_email = (isset($_POST['To_Email'])) ? $_POST['To_Email'] : '';
$subject = (isset($_POST['Subject'])) ? $_POST['Subject'] : '';
$message = (isset($_POST['Message'])) ? $_POST['Message'] : '';
$mail= new PHPmailer();
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->Host = "localhost";
$mail->Port = 25;
$mail->SMTPSecure = "none";
$mail->SMTPAuth = false;
$mail->addReplyTo($from_email, $from_name);
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->addAddress($to_email, $to_name);
$mail->Subject = $subject;
$mail->Body = '<html>'.$message.'</html>';
if(!$mail->Send()){
echo $mail->ErrorInfo;
}else{
echo 'Email inviata correttamente!';
}
$mail->SmtpClose();
unset($mail);
?>
On the Google Apps Script side, you can review the message to be sent by using UrlFetchApp.getRequest(). For example:
// Log readable JSON object
Logger.log(
JSON.stringify(
UrlFetchApp.getRequest(url,options),
null, 2 ));
Here's what it logs:
[15-05-06 22:23:35:144 EDT] {
"headers": {
"X-Forwarded-For": "99.224.168.137"
},
"useIntranet": false,
"followRedirects": true,
"payload": "From_Name=Fix+Name&Subject=subject_param&Message=body&From_Email=fix_mail#domain.com&To_Email=email#example.com&To_Name=name_param",
"method": "post",
"contentType": "application/x-www-form-urlencoded",
"validateHttpsCertificates": true,
"url": "http://www.example.com/willy.php"
}
Based on that, it appears that your function has prepared a POST request that should match your PHP.
Next, check the result of the POST itself. To that, first use the muteHttpExceptions option, then look for and handle the return code in your function by using HttpResponse.getResponseCode(). Furthermore, to obtain the readable text from the response, use response.getContentText(). Here's how that might look:
function sendEXTmail(name,email,subject,body) {
name = name || "name_param";
email = email || "email#example.com";
subject = subject || "subject_param";
body = body || "body";
var url = "http://www.example.com/willy.php";
var options = {
"muteHttpExceptions": true,
"method": "post",
"payload": {
"From_Name": "Fix Name",
"From_Email": "fix_mail#domain.com",
"To_Name": name,
"To_Email": email,
"Subject": subject,
"Message": body
}
};
// Log readable JSON object
Logger.log(
JSON.stringify(
UrlFetchApp.getRequest(url,options),
null, 2 ));
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
if (rc !== 200) {
// Failure - log it
Logger.log( "Error %s: %s", rc, response.getContentText())
}
return response.getContentText();
}
Try this with your real URL, and see what you get back. If it's a 200, then the Google Apps Script side of the exchange has worked properly. If not, the response should tell you more about the nature of the failure, and help you along to a solution.