I am trying to send an email with mailguns PHP api:
define('MAILGUN_KEY', 'key-ExamPle3xAMPle');
define('MAILGUN_DOMAIN', 'example.com');
$mailgun = new Mailgun\Mailgun(MAILGUN_KEY);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#signstoptt.com',
'to' => $email,
'subject' => 'Sign Stop mailing list confirmation.',
'html' => "
Hello{$name},</br></br>
This is a test."
]);
I have even tried to use array() instead of [ ].
I receive the following error in my php error log:
MissingRequiredParameters
It implies that what I am passing to the post function is incomplete or incorrect. upon inspecting the post function in the RestClient, I see that the function requires 2 arrays and not 1, so I tried adding a 2nd array with message attachments and it just got more errors, this time with guzzle (a dependency for mailgun)
[26-Jan-2015 14:32:50 UTC] PHP Fatal error: Uncaught exception 'Mailgun\Connection\Exceptions\MissingRequiredParameters' with message 'The parameters passed to the API were invalid. Check your inputs!' in C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php:187
Stack trace:
#0 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php(116): Mailgun\Connection\RestClient->responseHandler(Object(Guzzle\Http\Message\Response))
#1 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Mailgun.php(106): Mailgun\Connection\RestClient->post('signstoptt.com/...', Array, Array)
#2 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Mailgun.php(53): Mailgun\Mailgun->post('signstoptt.com/...', Array, Array)
#3 C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\subscribe.php(26): Mailgun\Mailgun->sendMessage('signstoptt.com', Array)
#4 in C:\Users\Zachary\Documents\NetBeansProjects\SS_MailingList\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php on line 187
Has anyone else had this problem. I am running the site on a glassfish server setup by netbeans. I also used composer to install mailgun and its dependencies.
EDIT: Added more information.
init.php
<?php
require_once 'vendor/autoload.php';
define('MAILGUN_KEY', 'key-854743a7e');
define('MAILGUN_PUBKEY', 'pubkey-b00e47d7');
define('MAILGUN_DOMAIN', 'example.com');
define('MAILGUN_LIST', 'customers#example.com');
define('MAILGUN_SECRET','xjhbJH7');
$mailgun = new Mailgun\Mailgun(MAILGUN_KEY);
$mailgunValidate = new Mailgun\Mailgun(MAILGUN_PUBKEY);
$mailgunOptIn = $mailgun->OptInHandler();
subscribe.php
<?php
require_once 'init.php';
if(isset($_POST['name'], $_POST['email']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$validate = $mailgunValidate->get('address/validate', [
'address' => $email
])->http_response_body;
if($validate->is_valid)
{
$hash = $mailgunOptIn->generateHash(MAILGUN_LIST, MAILGUN_SECRET, $email);
$result = $mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#example.com',
'to' => $email,
'subject' => 'example mailing list confirmation.',
'html' => "
Hello{$name},</br></br>
You submitted a request to join our mailing list, to confirm this subscription please click on the link provided below.</br></br>
http://localhost:8000/confirm.php?hash={$hash}"
]);
$mailgun->post('lists/' . MAILGUN_LIST . '/members', [
'name' => $name,
'address' => $email,
'subscribed' => 'no'
]);
header('Location: ./');
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Subscribe | Mailing list</title>
</head>
<body>
<div class="container">
<form action="subscribe.php" method="post">
<div class="field">
<label>
Name
<input type="text" name="name" autocomplete="off">
</label>
</div>
<div class="field">
<label>
Email
<input type="text" name="email" autocomplete="off">
</label>
</div>
<input type="submit" value="Subscribe" class="button">
</form>
</div>
</body>
</html>
You forgot the text key which is used when html isn't available by the mail client.
Your code will look like
define('MAILGUN_KEY', 'key-ExamPle3xAMPle');
define('MAILGUN_DOMAIN', 'example.com');
$mailgun = new Mailgun\Mailgun(MAILGUN_KEY);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#signstoptt.com',
'to' => $email,
'subject' => 'Sign Stop mailing list confirmation.',
'text' => 'Hello ' . $name . ', this is a test.',
'html' => '
Hello ' . $name . ',</br></br>
This is a test.'
]);
By the way; I recommend always using single quotes or double quotes for readability.
Related
I an setting up a website to send SMS automatically by API key Nexmo. But whene I add my variables into the Nexmo code, this one not work. How can I add my variables please?
I added my php variables to the Nexmo SMS default code but no result, but whene I trayed there code the stuff work fine
my file phone.php , with $row["phone_number"]=212981416807 at this exemple
$text1 = "Hello";
$text2 = " this is my company";
$MyNexmoID_Account = "3896321";
$MyNexmoAPI_Key = "yhg784frds78jkim";
$to = $row["phone_number"];
$from = "my company";
$text = "$text1 $text2";
// Code to Send SMS with Code Recharge ------
require_once "vendor/autoload.php";
//composer require nexmo/client;
$basic = new \Nexmo\Client\Credentials\Basic('$MyNexmoID_Account', '$MyNexmoAPI_Key');
$client = new \Nexmo\Client($basic);
$message = $client->message()->send([
'to' => '$to',
'from' => '$from',
'text' => '$text'
]);
if ($message && $client && $basic){echo " Recharge Code Sent Correctlly.";}else{echo "Failed! Recharge Code Not Sent.";}
// End Code to Send SMS with Code Recharge -----
This is default Nexmo code:
require_once "vendor/autoload.php";
//composer require nexmo/client;
$basic = new \Nexmo\Client\Credentials\Basic('3896321', 'yhg784frds78jkim');
$client = new \Nexmo\Client($basic);
$message = $client->message()->send([
'to' => '212981416807',
'from' => 'Nexmo',
'text' => 'Hello Nexmo'
]);
You don't need to quote variables. Try this:
$message = $client->message()->send([
'to' => $to,
'from' => $from,
'text' => $text
]);
Not sure if you have corrected this but do check your country code, I had a similar error with variable (also do listen to Michael Heap), where the hard code for the US phone number was 19091234567 and my database number was 9091234567. Unlike Twilio, Nexmo needs the country code. Hope it helps.
Ever since I made a change to a send file, I am getting around 20 spam submissions a day on a form. Before the change there was never spam.
The subtle modifications to my send file are shown below. The change solely consisted of how I was getting the POST data. The commented code below was my original and non-commented is what it is now.
$to_requester = Communication::mail_api($_POST, null, $template, 1, "{$_SERVER['DOCUMENT_ROOT']}/PDFs/{$pdf_downloaded}.pdf");
//$to_requester = Communication::mail_api($_POST, null, $template, 1, "../PDFs/" . $file_mapping[$_POST['pdf_downloaded']] . ".pdf");
There are several parts to my form. The process goes in this order:
Submission to Salesforce
Information sent to my database (via ajax)
Notification emails are sent to the user and myself (via ajax)
The spam submissions that are occurring are only submitted to salesforce. They never touch my send file (this includes the db submission and email notifications). The change I noted above is in the send file, so I have no idea why this would have any effect.
I have jQuery validation setup on the form itself.
The salesforce id and other information is held in a config file and called in the form file.
The submissions are entering salesforce like this:
The name/company fields are being filled with some sort of id/code. Again, the send file or database are not being reached with these submissions. The send file is reached with AJAX communicating in-between.
What could be causing these spam submissions? Is there anything I can do validation wise to make sure this spam is not submitted?
Form
<form action="<?php echo $config['sf_url']; ?>" method="POST" id="pdfForm">
<input type=hidden name="oid" value="<?php echo $config['oid']; ?>">
<input type=hidden name="retURL" value="<?php echo $config['retUrl']; ?>">
<input type="text" class="input block" id="first_name" maxlength="40" name="first_name"placeholder="First Name *">
<input type="text" class="input block" id="last_name" maxlength="80" name="last_name" placeholder="Last Name *">
<input type="email" class="input block" id="email" maxlength="80" name="email" placeholder="Email *">
<input id="pdfButton" class="button" type="submit" value="Download File">
</form>
Config
<?php
function getConfig($key)
{
$db = [
'username' => 'user',
'pass' => 'password',
'dbname' => 'db',
];
$ar = [
'sf' => [
'oid' => 'real id',
'sf_url' => 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8',
'retUrl' => 'https://example.com',
],
'pdo' => new PDO("mysql:host=localhost;dbname={$db['dbname']}", $db['username'], $db['pass'])
];
if(array_key_exists($key, $ar))
return $ar[$key];
}
Send file
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'classes/Communication.php';
require_once '../config.php';
if ($_SERVER['REQUEST_METHOD'] != 'POST')
exit();
$file_mapping = [
//Index
'Linear Structure' => 'Belt_Driven_Linear_1_3D', //LM Index
'Dynamic Structure' => 'Belt_Driven_Linear_5_3D', //LM MH Index
//LM
'Ball-Screw Application' => 'Belt_Driven_Linear_2_3D',
'Belt-Driven Structure' => 'Belt_Driven_Linear_6_3D',
'Linear Motion Enclosure' => 'Belt_Driven_Linear_7_3D'
];
$first_name = trim(htmlspecialchars($_POST['first_name']));
$last_name = trim(htmlspecialchars($_POST['last_name']));
$email = trim(htmlspecialchars($_POST['email']));
$phone = trim(htmlspecialchars($_POST['phone']));
$company = trim(htmlspecialchars($_POST['company']));
$pdf_downloaded = trim(htmlspecialchars($_POST['pdf_downloaded']));
$page_name = $_POST['page_name'];
$hasError = false;
try {
$config = getConfig('db');
$sent = false;
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$consult_insert = "
INSERT INTO pdf_submissions
(first_name, last_name, email, phone, company, date, pdf_downloaded, page_source)
VALUES(?,?,?,?,?,NOW(),?,?)
";
$consult_stmt = $con->prepare($consult_insert);
$consult_stmt->execute(array($first_name, $last_name, $email, $phone, $company, $pdf_downloaded, $page_name));
if (!array_key_exists($pdf_downloaded, $file_mapping)) {
$date = new DateTime();
$hasError = true;
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: The file selected could not be found in the file mapping. {$pdf_downloaded}.", FILE_APPEND);
}
} catch (PDOException $e) {
// echo "Connection failed: " . $e->getMessage();
}
if ($hasError !== true) {
/************************ Start to Requester ******************************/
$placeholders = [
'{first_name}',
'{last_name}',
'{phone}',
'{company}',
'{email}',
'{pdf_downloaded}'
];
$values = [
htmlentities($_POST['first_name']),
htmlentities($_POST['last_name']),
htmlentities($_POST['phone']),
htmlentities($_POST['company']),
htmlentities($_POST['email']),
htmlspecialchars($_POST['pdf_downloaded']),
];
$template = str_replace($placeholders, $values, file_get_contents("templates/pdf_to_requester.html"));
// Mail subject line goes here
$_POST['subject'] = 'Subject';
$_POST['h:Reply-To'] = 'sales#example.com';
$to_requester = Communication::mail_api($_POST, null, $template, 1, "{$_SERVER['DOCUMENT_ROOT']}/PDFs/{$pdf_downloaded}.pdf");
if (!$to_requester) {
$msg = [
'status_code' => 500,
'status_message' => 'Email Failed to send.'
];
echo json_encode($msg);
}
/************************ End to Requester ******************************/
/************************ Start to Domain ******************************/
$placeholders = [
'{first_name}',
'{last_name}',
'{email}',
'{phone}',
'{company}',
'{file_requested}',
'{page_name}'
];
$values = [
$first_name = trim(htmlspecialchars($_POST['first_name'])),
$last_name = trim(htmlspecialchars($_POST['last_name'])),
$email = trim(htmlspecialchars($_POST['email'])),
$phone = trim(htmlspecialchars($_POST['phone'])),
$company = trim(htmlspecialchars($_POST['company'])),
$pdf_downloaded = trim(htmlspecialchars($pdf_downloaded)),
$page_name = $_POST['page_name'],
];
$template = str_replace($placeholders, $values, file_get_contents("templates/pdf_to_domain.html"));
// Mail subject line goes here
$_POST['subject'] = 'Subject';
$_POST['h:Reply-To'] = 'sales#example.com';
$_POST['sendTo'] = "info#example.com";
$to_company = Communication::mail_api($_POST, null, $template, 0);
/************************ End to Domain ******************************/
if (!$to_company) {
$msg = [
'status_code' => 500,
'status_message' => 'Email was not sent.'
];
} else {
$msg = [
'status_code' => 200,
'status_message' => 'Check your Email.'
];
}
echo json_encode($msg);
JS
$("form#pdfForm").submit(function (form, e) {
console.log(send);
if(!send)
{
return false;
console.log("Should never touch this " + send);
}
var formData = new FormData(this);
$.ajax({
url: 'https://example.com/php',
type: 'POST',
data: formData,
success: function (e) {
$.LoadingOverlay("hide");
},
cache: false,
contentType: false,
processData: false
});
});
I've got the following php file below. When I run it from the terminal, it works great. However, when I open php file in the browser, I get the following exception:
Fatal error: Uncaught exception 'Twilio\Exceptions\EnvironmentException' with message 'SSL certificate problem: unable to get local issuer certificate' in /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Http/CurlClient.php:41 Stack trace: #0 /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Rest/Client.php(208): Twilio\Http\CurlClient->request('POST', 'https://api.twi...', Array, Array, Array, 'AC9fc89840f15b3...', 'd1db324eb375a2e...', NULL) #1 /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Domain.php(70): Twilio\Rest\Client->request('POST', 'https://api.twi...', Array, Array, Array, NULL, NULL, NULL) #2 /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Version.php(64): Twilio\Domain->request('POST', '2010-04-01/Acco...', Array, Array, Array, NULL, NULL, NULL) #3 /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Version.php(216): Twilio\Version->request('POST', '/Accounts/AC9fc...', Array, Array, Array, NULL, NULL, NULL) #4 /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Rest/Api/V2010/Account/MessageList.php(70): Twili in /Applications/AMPPS/www/vendor/twilio/sdk/Twilio/Http/CurlClient.php on line 41
Here is my code:
<?php // sendMessageTwilio.php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'XXXXXXXXXX';
$auth_token = 'XXXXXXXXXX';
// In production, these should be environment variables. E.g.:
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]
// A Twilio number you own with SMS capabilities
$twilio_number = "+XXXXXXXX";
$client = new Client($account_sid, $auth_token);
$client->messages->create(
// Where to send a text message (your cell phone?)
'+XXXXXXXXXXX',
array(
'from' => $twilio_number,
'body' => 'Testing From Website New!'
)
);
$number = $question = '';
if (isset($_POST['number'])){
$number = $_POST['number'];
$out = "Number: $number";
}
if (isset($_POST['question'])){
$question = $_POST['question'];
$out = $out." Question: $question";
}
else $out = "";
echo <<<_END
<html>
<head>
<title>Student Feedback</title>
</head>
<body>
<pre>
Enter phone number and question
<b>$out</b>
<form method="post" action="sendMessageTwilio.php">
Phone Number: <input type="text" name="number" size="17">
Question: <input type="text" name="question" size="17">
<input type="submit" value="Send Message">
</form>
</pre>
</body>
</html>
_END;
I'm using the composer to get all the necessary files set up.
Thanks all!
Linux servers usually have the ca_cert.pem in place. Follow these steps to fix your issue
https://support.twilio.com/hc/en-us/articles/235279367-Twilio-PHP-helper-library-SSL-certificate-problem-on-Windows
UPDATE
Here is my code
$http = new Services_Twilio_TinyHttp(
'https://api.twilio.com',
array('curlopts' => array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
))
);
$sid = 'ACfb185500bf13ce37c37fd2e13dsdfsdf';
$token = '4be5dcdb74e4cbd50d642a56b1fasdf2';
$client = new Services_Twilio($sid, $token, "2010-04-01", $http);
$message = $client->account->messages->sendMessage(
'+441231231231', // From a Twilio number in your account
'+441231231231,
'OTP for login is: 1234'
);
You need to set curl options to suppress the SSL verification
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
i have written this code for sending emails
Route::post('contact', function(){
$inputs = Input::all();
$rules = array(
'email' => 'required|email',
'name' => 'required|min:2',
'message' => 'required',
'recaptcha_response_field' => 'required|recaptcha',
);
$validator = Validator::make($inputs, $rules);
if($validator->passes()){
$fromEmail = Input::get('email');
$fromName = Input::get('name');
$subject = Input::get('subject');
$data = array('message' => Input::get('message'));
$toEmail = 'info#danielchikaka.com';
$toName = 'Daniel Chikaka';
Mail::send('emails.contact', $data, function($message) use ($toEmail, $toName, $fromEmail, $fromName, $subject){
$message->to($toEmail, $toName)->from($fromEmail, $fromName)->subject($subject);
});
return Redirect::to('/');
}
return Redirect::to('/#contact')->withInput()->withErrors($validator);
});
and my view emails.contact is
<html>
<body>
<p><b>Email From:</b> {{$fromName}} of {{$fromEmail}}</p>
<p><b>Subject:</b> {{$subject}}</p>
<b> Message:</b> <br>
</html> {{$data}}
</body>
but whenever i send email all i get is :
Email From:{{$fromName}} of {{$fromEmail}}
Subject: {{$subject}}
Message:
{{$data}
why my view does not pick up the data from Mail Class?
Make sure your view has the blade extension:
views/emails/contact.blade.php
Your $data array consists of only the variable message. So, in your blade template only {{$message}} will work. Ensure that you are passing all the variables required in your view into the $data array.
$data = array(
'message' => Input::get('message'),
'fromName' => Input::get('name'),
'fromEmail'=> Input::get('email')
);
Now, in your contact.blade.php you can use them as normal variables {{$formName}}, {{$fromEmail}} etc;
Also, since you are using blade templating, ensure that your view file is having proper extension i.e contact.blade.php
i have found a solution to my problem:
$fromEmail = Input::get('email');
$fromName = Input::get('name');
$subject = Input::get('subject');
$data = array('content' => Input::get('message'));
$toEmail = 'info#danielchikaka.com';
$toName = 'Daniel Chikaka';
Mail::send('emails.contact', $data, function($message) use ($toEmail, $toName, $fromEmail, $fromName, $subject){
$message->to($toEmail, $toName)->from($fromEmail, $fromName)->subject($subject);
});
and in the view has to be:
<html>
<body>
{{$content}}
</html>
</body>
Important:
Never use {{$message}} in contact view file, according to Taylor Otwell, that is reserved in email view files
Hope this will help someone one day!
I'm using a link to name a parameter that I need in a form on the next page. Here is the link code:
echo $this->Html->link('Email', array('controller' => 'emails', 'action' => 'add', 'contact_email' => $model), array('class' => 'button add'));
The purpose of this is to save an email to the database, and then send the email (both of which work).
I want to return to the page that they were on when they clicked the link, but don't know how to access that model and id after they've gone through two more page...
Here's add.ctp
<div class="universities form">
<?php echo $this->Form->create('Email');?>
<fieldset>
<legend><?php __('Add Email'); ?></legend>
<?php
echo $this->Form->input('subject');
echo $this->Form->input('email_text');
echo $this->Form->hidden('email', array('value' => $this->params['named']['contact_email']));
echo $this->Form->hidden('user_from', array('value' => $this->Session->read('User.id')));
echo $this->Form->hidden('created', array('value' => date("Y-m-d")));
echo $this->Form->hidden('modified', array('value' => date("Y-m-d")));
echo $this->Form->hidden('model', array('value' => $this->params['named']['model']));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
The real issue -- where to redirect?
$this->redirect(array('controller' => $this->data['Email']['model'], 'action' => 'view', $this->data['model']['id']));
After implementing answer one, I get these errors on redirect (email saves and sends successfully though, so its just redirect issue).
Notice (8): Undefined property: Email::$enabled [CORE/cake/libs/controller/component.php, line 142]
Code | Context
$component =& $this->_loaded[$name];
if ($component->enabled === true && method_exists($component, 'beforeRedirect')) {
Component::beforeRedirect() - CORE/cake/libs/controller/component.php, line 142
Controller::redirect() - CORE/cake/libs/controller/controller.php, line 678
EmailsController::add() - APP/controllers/emails_controller.php, line 54
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83
Warning: mkdir() [http://php.net/function.mkdir]: Permission denied in /Users/jwg2s/Sites/fundvista/cake/libs/folder.php on line 498
Warning (2): Cannot modify header information - headers already sent by (output started at /Users/jwg2s/Sites/fundvista/cake/libs/debugger.php:673) [CORE/cake/libs/controller/controller.php, line 742]
Code | Context
header - [internal], line ??
Controller::header() - CORE/cake/libs/controller/controller.php, line 742
Controller::redirect() - CORE/cake/libs/controller/controller.php, line 721
EmailsController::add() - APP/controllers/emails_controller.php, line 54
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83
Warning: mkdir() [http://php.net/function.mkdir]: Permission denied in /Users/jwg2s/Sites/fundvista/cake/libs/folder.php on line 498
What I would suggest, is to build a full return URI using:
$this->params['controller']
$this->params['action'];
$this->params['pass'];
So it would look something like this:
$returnUrl = $this->params['controller'] . '/' . $this->params['action'] . '/' . implode('/', $this->params['pass']);
// let's also replace the slashes with, say, underscores
$returnUrl = str_replace('/', '_', $returnUrl);
echo $this->Html->link('Email', array('controller' => 'emails', 'action' => 'add', 'contact_email' => $model, 'returnUrl' => $returnUrl), array('class' => 'button add'));
in add.ctp
echo $this->Form->hidden('returnUrl', array('value' => $this->params['named']['returnUrl']));
and in email's controller
$this->redirect('/' . str_replace('_', '/', $this->data['Email']['returnUrl']));
$this->redirect($this->referer(array('action' => 'index')));
where index is your default action if the referring link doesn't exist.
read up here
e.g your user is on content/view/my-content, he clicks emails/add, fills in his details, submits. the referring page is content/view/my-content, so he (should) be redirected back there.
I added this to app_controller.php:
public function sendEmail($to,$from,$subject,$body,$headers=array(),$save_to_db=true)
{
if($save_to_db == true)
{
//do model crap here
$this->Email->create();
$data = array(
'email' => $to,
'subject' => $subject,
'email_text' => $body,
'user_from' => $from,
// map fields here
);
if($this->Email->save($data) == false)
{
$this->log("Email to '$to' from '$from' with subject '$subject' failed to save into the database!");
}
} // end save to db
$email = new EmailComponent();
//$email->startup($this);
//reeset email component
$email->reset();
/* SMTP Options */
$email->smtpOptions = array(
'port'=>'25',
'timeout'=>'30',
'host' => 'smtp.gmail.com',
'username'=>'###########',
'password'=>'###########',
);
/* Set delivery method */
//$email->delivery = 'smtp';
$email->from = $from;
$email->to = $to;
$email->subject = $subject;
$email->replyTo = $from;
$email->from = '############ <' . $subject . '>';
$email->sendAs = 'html'; //Send as 'html', 'text' or 'both' (default is 'text')
$success = $email->send($this->data['Email']['email_text']);
if($success == false)
{
$this->log("Email to '$to' from '$from' with subject '$subject' failed to send!");
}
return true;
} // end sendEmail
And then called the function after setting variables in my emails controller. (e.g. the $to, $from, $subject, $body, $headers)