Amazon SES RawMessage: Missing required header 'From' - php

use PHPMailer\PHPMailer\PHPMailer;
use Aws\Ses\SesClient;
use Aws\Ses\Exception\SesException;
require 'vendor/autoload.php';
if(!function_exists("sendmailalexraw")){
function sendmailalexraw($email,$subject,$messages,$definesender)
{
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
$sender = $definesender;
$sendername = 'Alex';
// Replace recipient#example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
$recipient = $email;
// Specify a configuration set.
$configset = 'ConfigSet';
// Replace us-west-2 with the AWS Region you're using for Amazon SES.
$region = 'eu-west-1';
$subject = $subject;
$htmlbody = <<<EOD
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please see the attached file for a list of customers to contact.</p>
</body>
</html>
EOD;
$textbody = <<<EOD
Hello,
Please see the attached file for a list of customers to contact.
EOD;
//// The full path to the file that will be attached to the email.
$att = 'path/to/customers-to-contact.xlsx';
// Create an SesClient.
$client = SesClient::factory(array(
'version'=> 'latest',
'region' => $region
));
// Create a new PHPMailer object.
$mail = new PHPMailer;
// Add components to the email.
$mail->setFrom($sender, $sendername);
$mail->addAddress($recipient);
$mail->Subject = $subject;
$mail->Body = $htmlbody;
$mail->AltBody = $textbody;
$mail->addAttachment($att);
$mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configset);
// Attempt to assemble the above components into a MIME message.
if (!$mail->preSend()) {
echo $mail->ErrorInfo;
} else {
// Create a new variable that contains the MIME message.
$message = $mail->getSentMIMEMessage();
}
// Try to send the message.
try {
$result = $client->sendRawEmail([
'RawMessage' => [
'Data' => $messages
]
]);
// If the message was sent, show the message ID.
$messageId = $result->get('MessageId');
echo("Email sent! Message ID: $messageId"."\n");
} catch (SesException $error) {
// If the message was not sent, show a message explaining what went wrong.
echo("The email was not sent. Error message: "
.$error->getAwsErrorMessage()."\n");
}
}
}
$email='example#gmail.com';
$subject='abc';
$messages='xyz';
$definesender='info#verifieddomain.net';
sendmailalexraw($email,$subject,$messages,$definesender);
?>
I am trying to send RawMessage with Amazon SES but I get :
The email was not sent. Error message: Missing required header 'From'.
Sender I use it's verified, my Amazon SES it's active (out of sendbox ) .
I am needing to send as RAW Message to create unsubscribe option for emails I am sening. As I read from documentation it have to be raw email to be able to add this parameters.Thank you !

You have to base64 encode the message :
$result = $client->sendRawEmail([
'RawMessage' => [
'Data' => base64_encode($messages)
]
]);

Since you're using AWS Ses, you could do it this way:
define('SENDER', 'Your name<a#a.com>');
define('RECIPIENT', 'b#b.com');
define('CCLIST', 'c#c.com');
define('REGION','your region');
define('SUBJECT','Your subject goes here');
$bodytext = "<h2>Your body goes here.</h2>" . PHP_EOL;
$bodytext .= "<p>Append as many rows as you want</p>";
define('BODY',$bodytext);
$client = SesClient::factory(array(
'version'=> 'latest',
'region' => 'your region'
));
$request = array();
$request['Source'] = SENDER;
$request['Destination']['ToAddresses'] = array(RECIPIENT);
$request['Destination']['CcAddresses'] = array(CCLIST);
$request['Message']['Subject']['Data'] = SUBJECT;
$request['Message']['Body']['Html']['Data'] = BODY;
try {
$result = $client->sendEmail($request);
$messageId = $result->get('MessageId');
echo("Email successfully sent! Message ID: $messageId"."\n");
} catch (Exception $e) {
echo("The email was not sent. Error message: ");
echo($e->getMessage()."\n");
}

Related

Adding SMTP to the php form Bootstrap

I have this form on my site:
https://bootstrapious.com/p/bootstrap-recaptcha
I want to add SMTP thanks to this:
https://www.lifewire.com/send-email-from-php-script-using-smtp-authentication-and-ssl-1171197
How to add this to the file contact.php (below) ?. He works independently. I need the form from Bootstrap to send emails via SMTP.
The smtp connection is correct. Only I can not deal with sending all data from the form in this way. This is done using the normal php mail function.
require_once "Mail.php";
$from = "Sandra Sender <mail#mail>";
$to = "Ramona Recipient <mail#mail>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "host";
$username = "mail";
$password = "haslo";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
contact.php
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Demo contact form <--->';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <--->';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message', 'name2' => 'Name2', 'surname2' => 'Surname2', 'selekt' => 'Wybrane');
$selectOption = $_POST['selekt'];
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = '---';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
Log errors:
PHP Fatal error: Uncaught Error: Class 'Mail' not found in /home/lukaste/domains/lukaste.vdl.pl/public_html/luw2/contact.php:88, referer: http://lukaste.vdl.pl/luw2/
mod_fcgid: stderr: Stack trace:, referer: http://lukaste.vdl.pl/luw2/
mod_fcgid: stderr: #0 {main}, referer: http://lukaste.vdl.pl/luw2/
mod_fcgid: stderr: thrown in /home/lukaste/domains/lukaste.vdl.pl/public_html/luw2/contact.php on line 88, referer: http://lukaste.vdl.pl/luw2/
File does not exist: /home/lukaste/domains/lukaste.vdl.pl/public_html/404.shtml, referer: http://lukaste.vdl.pl/luw2/
Line 88:
$smtp = Mail::factory('smtp',
All send mail:
// Send email
require_once "Mail.php";
$from = "Sandra Sender <kontakt#graftet.pl>";
$to = "Ramona Recipient <lukaste90#gmail.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "s12.linuxpl.com";
$username = "kontakt#graftet.pl";
$password = "eRsPdWgB";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
/ edit, contact.php with phpmailer. No errors in the logs. The form does not send.
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Demo contact form <lukaste90#gmail.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <lukaste90#gmail.com>';
// subject of the email
$subject = 'Wiadomość z formularz wps.lublin.uw.gov.pl';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Imię', 'surname' => 'Nazwisko', 'phone' => 'Telefon', 'email' => 'Email', 'message' => 'Wiadomość', 'pesel' => 'PESEL', 'sprawa' => 'Numer sprawy', 'rodzaj' => 'Rodzaj zapytania', 'dotyczy' => 'Dotyczy');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = '6LcqdV4UAAAAAOWvJblsdZuxVTHJr3-uDCXutqxM';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "serwer"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "serwer"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "#"; // SMTP account username
$mail->Password = "pass"; // SMTP account password
$mail->SetFrom('mail', 'First Last');
$mail->AddReplyTo("mail","First Last");
$mail->Subject = "Wiadomosc";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "mail";
$mail->AddAddress($address, "John Doe");
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}

Sendgrid php send to multiple recipients

I have simple sendgrid php script to send email, only issue here is that i need to add more recipients, so this code works only for one recipient, i was looking at official documentation but was unable to find any useful info, is there anyone who knows how and what i need to change here to add more recipients/emails.
function sendEmail($subject, $to, $message) {
$from = new SendGrid\Email(null, "sample#email.com");
$subject = $subject;
$to = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/html", $message);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = 'MY_KEY';
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
}
The SendGrid\Mail class supports adding multiple to addresses through the SendGrid\Personalization class.
You can see an example here: https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L31-L35
Think of a Personalization as the envelope for your email. It holds the recipient's addresses and other similar data. Each Sendgrid\Mail object, must have at least one Personalization.
Through the constructor you are using, a Personalization object is already created for you, see here: https://github.com/sendgrid/sendgrid-php/blob/master/lib/helpers/mail/Mail.php#L951-L958
You can create a Mail object without this and later add your own Personalization.
In the end, this is how I have managed to do this and it's working good.
function sendEmail($subject, $to, $message, $cc)
{
$from = new SendGrid\Email(null, "sample#email.com");
$subject = $subject;
$to = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/html", $message);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
foreach ($cc as $value) {
$to = new SendGrid\Email(null, $value);
$mail->personalization[0]->addCC($to);
}
$apiKey = 'MY_KEY';
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
}
If someone is still looking for an answer to how to add multiple emails in To, Cc, and Bcc, Using SendGrid, here is what helped me.
First, you need to add an associative array like this:
for multiple emails in to (recipients):
$tos = [
"example1#example.com" => "User 1",
"example1#example.com" => "User 2"
];
and in your SendMail class use this $email->addTos($tos); instead of $email->addTo;
Similarly, for multiple Cc use
$email->addCcs($cc);
and for Bcc
$email->addBccs($bcc);
Here is the link to see more details sendgrid php
function makeEmail($to_emails = array(),$from_email,$subject,$body) {
$from = new SendGrid\Email(null, $from_email);
$to = new SendGrid\Email(null, $to_emails[0]);
$content = new SendGrid\Content("text/plain", $body);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$to = new SendGrid\Email(null, $to_emails[1]);
$mail->personalization[0]->addTo($to);
return $mail;
}
function sendMail($to = array(),$from,$subject,$body) {
$apiKey = 'your api key';
$sg = new \SendGrid($apiKey);
$request_body = makeEmail($to ,$from,$subject,$body);
$response = $sg->client->mail()->send()->post($request_body);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());
}
$to = array('test1#example.com','test2#example.com');
$from = 'from#example.com';
$subject = "Test Email Subject";
$body = "Send Multiple Person";
sendMail($to ,$from,$subject,$body);
Now Sendgrid provides an easy way for sending single mail to multiple recipients,
it provides Mail::addTos method in which we can add multiple mails to whom we want to send our mail,
we have to pass associative array of user emails and user names into addTos.
see below example:
$tos = [
//user emails => user names
"user1#example.com" => "Example User1",
"user2#example.com" => "Example User2",
"user3#example.com" => "Example User3"
];
$email->addTos($tos);
If you want to see Full example which is provided in sendgrid-php github library then i have included it below, so you can understand the whole example:
<?php
require 'vendor/autoload.php'; // If you're using Composer (recommended)
// Comment out the above line if not using Composer
// require("<PATH TO>/sendgrid-php.php");
// If not using Composer, uncomment the above line and
// download sendgrid-php.zip from the latest release here,
// replacing <PATH TO> with the path to the sendgrid-php.php file,
// which is included in the download:
// https://github.com/sendgrid/sendgrid-php/releases
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test#example.com", "Example User");
$tos = [
"test+test1#example.com" => "Example User1",
"test+test2#example.com" => "Example User2",
"test+test3#example.com" => "Example User3"
];
$email->addTos($tos);
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage(). "\n";
}
Ref:
https://github.com/sendgrid/sendgrid-php/blob/master/USE_CASES.md#send-an-email-to-multiple-recipients

AWS SES SendEmail specifying a name gives 403 Forbidden response

I am trying to set up a mail system with Amazon SES service. All is good and working if I use only the email address in "Source" parameter. If I try to add a name, I get a 403 Forbidden HTTP error.
In my PHP code I use AWS SDK:
$client = Aws\Ses\SesClient::factory(array(
'key' => 'MYAWSKEYXXXXXXXXXX',
'secret' => 'MYAWSSECRETXXXXXXXXXXX',
'version'=> 'latest',
'region' => 'us-east-1'
));
$request = array();
$request['Source'] = "sender#example.com";
$request['Destination']['ToAddresses'] = array("receiver#example.com");
$request['Message']['Subject']['Data'] = 'Mail Subject';
$request['Message']['Body']['Html']['Data'] = 'mail body in HTML: <b>Hello!</b>';
try {
$result = $client->sendEmail($request);
$messageId = $result->get('MessageId');
$message = "Email sent! Message ID: $messageId";
} catch (Exception $e) {
$message = "The email was not sent. Error message: ";
$message .= $e->getMessage();
}
This code works great, because I have correctly set up my email source in the AWS console with the correct policy. So "sender#example.com" in this example can correctly send the email.
Then, if I try to add a name to the "Source" param, I don't have any success. I tried:
$request['Source'] = "My Name <sender#example.com>";
OR
$request['Source'] = "'My Name' <sender#example.com>";
OR
$request['Source'] = "'My Name'<sender#example.com>";
OR
$request['Source'] = "'My Name <sender#example.com>'";
OR
$request['Source'] = '"My Name" <sender#example.com>';
OR
$request['Source'] = '"My Name"<sender#example.com>';
OR
$request['Source'] = '"My Name <sender#example.com>"';
None of the above work.
Does anybody have any idea on how to use SES sendEmail with email names?
Some answers I saw here, like this one, simply don't work. I need to use sendEmail and PHP SDK.

How to change the name text of sender when sending mail with Swift Mailer v3.3.2

I'm using Swift Mailer v3.3.2 to send emails from my app and I need to be able to change the text of the sender.
My code looks like this:
//Sending email
$swift = email::connect();
$email_message = new View('email/email_template');
$subject = "Subject here";
$from = "subdomain#domain.org";
$email_message->content_email = new View('email/content/signup');
$email_message->content_email->user = $user;
$message = $email_message;
$recipients = new Swift_RecipientList;
$recipients->addTo($user->email);
// Build the HTML message
$message = new Swift_Message($subject, $message, "text/html");
if ($swift->send($message, $recipients, $from)) {
;
} else {
;
}
$swift->disconnect();
I want to be able to set the name text of the sender as 'Senders_Name Senders_Surname', even though the sender is still subdomain#domain.org
Any clue on how to do that?
After line
$message = new Swift_Message($subject, $message, "text/html");
you should add
$message->setFrom(new Swift_Address($from , 'Senders_Name Senders_Surname'));
The whole working script below (I've just tested it in 3.3.2 version):
<?php
require ('lib/Swift.php');
require('lib/Swift/Connection/SMTP.php') ;
$smtp = new Swift_Connection_SMTP();
$smtp->setServer('server');
$smtp->setUsername('username');
$smtp->setPassword('password');
$smtp->setEncryption($smtp::ENC_SSL);
$smtp->setPort(465);
$swift = new Swift($smtp);
$swift->connect();
$subject = "Subject here";
$from = 'test#email.com';
$message = 'test message';
$recipients = new Swift_RecipientList;
$recipients->addTo('mymail');
// Build the HTML message
$message = new Swift_Message($subject, $message, "text/html");
$message->setFrom(new Swift_Address($from , 'Senders_Name Senders_Surname'));
if ($swift->send($message, $recipients, $from)) {
;
} else {
;
}
$swift->disconnect();
Below image how the sender is displayed in email client (Thunderbird for me) so it works fine. If you test it in your email client make sure you don't have account from set as one of your mail accounts. In that case email client shows for example "Me" or sth else. The best for test just fill in addTo with your email and smtp settings and leave from and other parts unchanged

Fatal error: Call to undefined method stdClass::AddAddress() in PHP mailer

I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code.I need to have them query my database and send the e-mail to each e-mail address.It is working but email was send to the first e-mail address only, and got an error "Fatal error: Call to undefined method stdClass::AddAddress()".Where am I going wrong here?
<?php
$elist = $database->getRows("SELECT * FROM `emails`");
foreach($elist as $emails){
$frm = 'test#gmail.com';
$sub = 'Weekly Work Report';
ob_start();
include_once('mail_content.php');
$mail_body = ob_get_contents();
ob_end_clean();
$to = $emails['email'];
$mailstatus = lm_mail('1', '2', $to, '3', $frm, 'HR', $sub, $mail_body);
if ($mailstatus == 'ok') {
$response->redirect('index.php?com_route=user_report');
} else {
echo $mailstatus;
}
}
?>
function lm_mail($head_mid='',$head_mname='',$to_mid ,$to_mname='',$reply_mid,$reply_mname='',$subject,$body,$attachments='')
{
include_once 'phpmailer/mail_config.php';
if(SMTP_mail)
{
// Send SMTP Mails
$mail->From =$head_mid ; // From Mail id
$mail->FromName = $head_mname; // From Name
$mail->AddAddress($to_mid,$to_mname); // To Address
$mail->AddReplyTo($reply_mid,$reply_mname); // From Address
$mail->Subject=$subject;
$mail->Body = $mail_body.$body; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
return $mail->ErrorInfo;
}
else
{
return 'ok';
}
}
else
{
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->AddReplyTo($reply_mid,$reply_mname); // Sender address
$mail->AddReplyTo($reply_mid,$reply_mname); // replay to address
$address = $to_mid; // to addtesas
$mail->AddAddress($address, $to_mname);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($mail_body.$body);
if(!$mail->Send())
{
return $mail->ErrorInfo;
}
else { return 'ok'; }
}
}
In the first conditional of the lm_mail function call there is no object being instantiated.
if(SMTP_mail)
{
// No $mail object?
// Send SMTP Mails
$mail->From =$head_mid ; // From Mail id
Try adding:
if(SMTP_mail)
{
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
// Have to manually set language if PHPMailer can't determine
$mail->SetLanguage("en", 'includes/phpMailer/language/');
I'm guessing you are using SMTP, because I don't see where $mail comes from.
Since one email is sending, my guess is that phpmailer/mail_config.php sets up a $mail object and sets the SMTP_mail constant, and then it goes out of scope after the first function call and the file is only included once so it doesn't get defined again.
After that it wasn't defined as a PHPMailer object, so it is cast as a stdClass when you do the object assignment $mail->From = $head_mid.
Try taking the code out of mail_config.php and replicating it in your send function, or add a function to mail_config.php that provides a factory to getting a PHPMailer object that is configured for your needs.

Categories