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.
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 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).
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'm new to using EWS from Exchangeclient classes.
I'm looking for a simple example how to send an email with an attachment. I've found examples about how to send an email but not sending an email with an attachment.
This is my script:
$exchangeclient = new Exchangeclient();
$exchangeclient->init($username, $password, NULL, 'ews/Services.wsdl');
$exchangeclient->send_message($mail_from, $subject, $body, 'HTML', true, true);
function - PHP Classes:
function send_message($to, $subject, $content, $bodytype="Text", $saveinsent=true, $markasread=true) {
$this->setup();
if($saveinsent) {
$CreateItem->MessageDisposition = "SendOnly";
$CreateItem->SavedItemFolderId->DistinguishedFolderId->Id = "sentitems";
}
else
$CreateItem->MessageDisposition = "SendOnly";
$CreateItem->Items->Message->ItemClass = "IPM.Note";
$CreateItem->Items->Message->Subject = $subject;
$CreateItem->Items->Message->Body->BodyType = $bodytype;
$CreateItem->Items->Message->Body->_ = $content;
$CreateItem->Items->Message->ToRecipients->Mailbox->EmailAddress = $to;
if($markasread)
$CreateItem->Items->Message->IsRead = "true";
$response = $this->client->CreateItem($CreateItem);
$this->teardown();
if($response->ResponseMessages->CreateItemResponseMessage->ResponseCode == "NoError")
return true;
else {
$this->lastError = $response->ResponseMessages->CreateItemResponseMessage->ResponseCode;
return false;
}
}
You have to first save the email as a draft (with the appropriate message disposition), then CreateAttachment() so it has an attachment, then edit it with UpdateItem() so the message disposition is SendOnly. Then it will be sent.
See David Sterling's reply on this thread: http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/f7d5257e-ec98-40fd-b301-f378ba3080fd/ (It's about Meeting Requests but they work the same way.)
I am creating a function to send a notification email to a user using the phpMailer lib.
public function notify($address,$subject = '',$body = null,$mailer_options = array()) {
try {
$phpmailer = new PHPMailer($exceptions = true);
$phpmailer->CharSet = 'UTF-8';
$phpmailer->IsSMTP();
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPKeepAlive = true;
//$phpmailer->SMTPDebug = true;
$phpmailer->IsHTML(true);
$phpmailer->Host = ...
$phpmailer->Username = ...
$phpmailer->Password = ...
$phpmailer->From = ...
$phpmailer->FromName =...
$phpmailer->AddAddress($address);
$phpmailer->Subject = $subject;
$phpmailer->Body = $body;
$phpmailer->Send();
$phpmailer->ClearAllRecipients();
}
It works fine if i just send an email or sending multiple emails inside the class.
But if do
for($i=0;$i<3;$++)
{
$notification = new $Notification();
$notification->notify(...);
}
It retuns a blank page. No errors, messages, nothing.
Before you ask i have display_errors turned on.
What can it be?
It works fine if i just have one instance of phpmailer like this:
$phpmailer = new PHPMailer($exceptions = true);
(...)
for($i=0;$i<3;$i++)
{
$phpmailer->AddAddress('address');
$phpmailer->Subject = "";
$phpmailer->Body = "sasa";
$phpmailer->Send();
$phpmailer->ClearAllRecipients();
}
Remove the $ from new Notification:
for($i=0;$i<3;$++)
{
$notification = new Notification();
$notification->notify(...);
}
new $Notification will create a new instance from the value of variable $Notification.
That would only work if $Notification really contains "Notification" (assuming your class is named "Notification")
If you've turned display_errors on in your PHP script, but the server has disabled it by default, errors won't be displayed if there is a syntax error in your script.