JMail usage for cutsom component programming - joomla

My code works when the format is html.
<pre>
public function partOrder()
{
$input=JFactory::getApplication()->input;
$mailer =JFactory::getMailer();
$config =JFactory::getConfig();
$mailer->setSender(array("email#email.com","name"));
$mailer->addRecipient("somerecipient#somerecipent.com");
$body="Some html message";
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
$send =$mailer->Send();
$respond="";
if ( $send !== true ) {
$respond= 'Error sending email: ' . $send->message;
} else {
$respond= 'Mail sent';
}
echo $respond;
}
</pre>
When I use same function on controller for json format I get the "Mail Sent" message. But Mail doesn't reach to recipient;

I don't think there's anything wrong with your function.
However, I noticed that Gmail is quite picky when it comes which emails come trough to inbox:
All Global Configuration > Server > Mail Settings must be filled in and valid.
These settings have to be used for JMail configuration
// Initialize some variables
$app = JFactory::getApplication();
$mailer = JFactory::getMailer();
// Get mailer configuration
$mailfrom = $app->getCfg('mailfrom');
$fromname = $app->getCfg('fromname');
$sitename = $app->getCfg('sitename');
// Clean the email data
$contact_to = JMailHelper::cleanAddress( $data['contact_to'] );
$subject = JMailHelper::cleanSubject( $data['contact_subject'] );
$body = JMailHelper::cleanBody( $data['contact_message'] );
$reply_to_email = JMailHelper::cleanAddress( $data['contact_reply_to'] );
$reply_to_name = JMailHelper::cleanLine( $data['contact_reply_to_name'] );
// Construct mailer
$mailer
->addRecipient($contact_to)
->addReplyTo(array($reply_to_email, $reply_to_name))
->setSender(array($mailfrom, $fromname))
->setSubject($sitename . ': ' . $subject)
->setBody($body)
;
// Send email
$sent = $mailer->Send();

Related

Redirect link page is preventing my email from sending

I added this in email signature:
Test Website
testwebsite.com
==========
If you click testwebsite.com, it will redirect to my website mywebsite.com
Whenever I used testwebsite.com as part of the email signature on my site, the email notification is not sending. But if I changed that to mywebsite.com, the email notification is working fine.
==========
By the way, my email notification was integrated on mywebsite.com using SendMail in CodeIgniter framework.
Could you please help me why my marketing domain testwebsite.com is preventing the email notifications from sending successfully.
PS. I just used test website URLs in the above scenario for security purposes.
======
function send_email_template($template, $recipient, $subject = null, $vars = null) {
$ci = & get_instance();
$ci->load->model('default/m_settings');
//get site data
$website = $ci->M_website->getWebsite();
$ci->load->library('email');
$ci->email->clear();
$config['mailtype'] = 'html';
$ci->email->initialize($config);
// Set default subject.
if ($subject == null) {
// Try to find a "_subject" setting for the template specified.
$subject = $ci->m_settings->get($template . '_subject');
if ($subject) {
$subject = $subject->setting_value;
} else {
$subject = '';
}
}
$template = $ci->m_settings->get($template);
$body = htmlspecialchars_decode(cs_parse_vars($template->setting_value, $vars));
$body .= $ci->m_settings->get('global_email_footer')->setting_value;
$ci->email->set_newline("\r\n");
//get admin email
$ci->load->model('admin/M_administrator');
$admin_email = $ci->m_settings->get('admin_outgoing_email')->setting_value;
$email_sender_from = ($admin_email) ? $admin_email : 'no-reply#' . strtolower(preg_replace('/\s/', '-', $website['name']));
$ci->email->from($email_sender_from, $website['name']);
// _APPLICATION_ENV_ is set in /index.php
if (_APPLICATION_ENV_ != 'PRODUCTION') {
$recipient = _EMAIL_RECEPIENT_;
}
if ($recipient == '') {
#$recipient = 'jamygallardo#gmail.com';
}
$ci->email->to($recipient);
$ci->email->subject('[' . $website["name"] . '] ' . $subject);
$ci->email->message($body);
if ($ci->email->send()) {
return TRUE;
} else {
show_error('mailer error:' . $ci->email->print_debugger());
}
return TRUE;
}
Thanks,
Jamaica

Using Google ReCaptcha

I am keen on using Google ReCaptcha. I have got the captcha on the page using the public key but don't know how to use the private key in my form processor document:
<?php
//SMTP SETTINGS
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.webhost.co.nz'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ‘xxxxx#xxxxxxxx.co.nz'; // SMTP username
$mail->Password = ‘xxxxx##xxxxxx’; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port = 465;
$mail->isHTML(true); // Set email format to HTML
//SMTP SETTINGS
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
print_r($_POST);
$mailheader = "From: $email";
$to = "tony#finelinecreative.co.nz"; // Here is email send to
$subject = "Finelinecreative Enquiry";
$message = "Name: $name<br/>Email: $email<br/>Message: $message";
// Send the mail
$mail->From=$mail->Username;
$mail->FromName = 'finelinecreative';
$mail->addAddress($to);
$mail->addReplyTo($email, $email);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->IsHTML(true);
$result = $mail->send();
header('location: http://www.finelinecreative.co.nz/index.php/thanks');
?>
Ideas please?
There's a great tutorial at https://codeforgeek.com/2014/12/google-recaptcha-tutorial/ that explains it pretty well.
In essence, you're checking if the $_POST variable 'g-recaptcha-response' exists (which, by including recaptcha on your form, is sent along with the other values on the form). If it is, you send a file_get_contents call (sending the secret key, the g-recaptcha-response POST value, and the user's IP address). You decode the result of that (which is sent as JSON, and you probably want to access it as key-value pairs), and find out whether the query was successful.
This is the relevant portion of their implementation.
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
} else {
// Send the email. In your case, you can wrap pretty all of your preprocessor in this.
}

Set a different SMTP for Newsletter in Magento

i was wondering if it's possible to set two different SMTP server on Magento:
one for the Newsletter and one for the Magento System emails.
I saw around that is possible to set SMTP in template.php but that will affect all the emails. Is then possible two different ones?
Thank you all !!
Ps:
I tried to modify the file /app/code/core/Mage/Newsletter/Model/Template.php
as suggested on post :
Magento - How enable SMTP server authentication and secure transport?
and used the code in this way:
public function getMail()
{
if (is_null($this->_mail)) {
/*Start of added code to specify config*/
$my_smtp_host = 'smtp.mysmtp.com'; // Take it from Magento backoffice or you can specify it here
$my_smtp_port = '587'; // Take it from Magento backoffice or you can specify it here
$config = array(
'port' => $my_smtp_port, //optional - default 25
'auth' => 'login',
'username' => 'mylogin#email.it',
'password' => 'mypassword'
);
$transport = new Zend_Mail_Transport_Smtp($my_smtp_host, $config);
Zend_Mail::setDefaultTransport($transport);
/*End of added code to specify config*/
$this->_mail = new Zend_Mail('utf-8');
}
return $this->_mail;
}
Unfortunatly is taking the system smtp instead of using this one.
I also commented the two lines:
ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));
Any idea why is still using the system one?
Mail transport is set up and executed from these two functions
Mage_Core_Model_Email_Template -> send() in /app/code/core/Mage/Core/Model/Email/Template.php for Transactional Emails
Mage_Newsletter_Model_Template -> send() in /app/code/core/Mage/Newsletter/Model/Template.php for Newsletters
Here's the working module code I created to direct transactional emails through our email service provider. It is not a paste-in for the newsletter send() function!
Note that you will need to hard code the extra config items for your purposes as this code sample is missing the setup to add the fields to system config, but it should give you an idea of how the send() function needs to be changed for the Newsletter module. I personally don't use the Newsletter module as we have a service provider for promotional emails to keep from poisoning our domain by false flagging as a spam source.
public function send($email, $name = null, array $variables = array())
{
if (!$this->isValidForSend()) {
Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted
return false;
}
/* Set up mail transport to Email Hosting Provider SMTP Server via SSL/TLS */
$config = array(
'ssl' => Mage::getStoreConfig('system/smtp/ssl'), // option of none, ssl or tls
'port' => Mage::getStoreConfig('system/smtp/port'), // TLS 587 - SSL 465 - default 25
'auth' => Mage::getStoreConfig('system/smtp/auth'), // Auth type none, login, plain, CRAM-MD5
'username' => Mage::getStoreConfig('system/smtp/username'),
'password' => Mage::getStoreConfig('system/smtp/password')
);
/* Set up transport package to host */
$transport = new Zend_Mail_Transport_Smtp(Mage::getStoreConfig('system/smtp/host'), $config);
/* End transport setup */
$emails = array_values((array)$email);
$names = is_array($name) ? $name : (array)$name;
$names = array_values($names);
foreach ($emails as $key => $email) {
if (!isset($names[$key])) {
$names[$key] = substr($email, 0, strpos($email, '#'));
}
}
$variables['email'] = reset($emails);
$variables['name'] = reset($names);
// ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
// ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));
$mail = $this->getMail();
$setReturnPath = Mage::getStoreConfig(self::XML_PATH_SENDING_SET_RETURN_PATH);
switch ($setReturnPath) {
case 1:
$returnPathEmail = $this->getSenderEmail();
break;
case 2:
$returnPathEmail = Mage::getStoreConfig(self::XML_PATH_SENDING_RETURN_PATH_EMAIL);
break;
default:
$returnPathEmail = null;
break;
}
if ($returnPathEmail !== null) {
$mailTransport = new Zend_Mail_Transport_Sendmail("-f".$returnPathEmail);
Zend_Mail::setDefaultTransport($mailTransport);
}
foreach ($emails as $key => $email) {
$mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
}
$this->setUseAbsoluteLinks(true);
$text = $this->getProcessedTemplate($variables, true);
if($this->isPlain()) {
$mail->setBodyText($text);
} else {
$mail->setBodyHTML($text);
}
$mail->setSubject('=?utf-8?B?' . base64_encode($this->getProcessedTemplateSubject($variables)) . '?=');
$mail->setFrom($this->getSenderEmail(), $this->getSenderName());
try {
/* Send Transport, empty and log success */
$mail->send($transport); //transport object
$this->_mail = null;
Mage::log('Mailed to: ' . $this->getSenderEmail() . ' ' . $this->getSenderName() . ' ' .$this->getProcessedTemplateSubject($variables), null, 'email.log');
/* End */
}
catch (Exception $e) {
/* Or empty and log failure */
$this->_mail = null;
Mage::log('Failure: ' . $e, null, 'email.log');
Mage::logException($e);
return false;
/* End */
}
return true;
}

Sending multiple messages with swiftmailer - PHP

I'm trying to send e-mails using swiftmailer. I want to send a message to someone who fills out a form, and to myself. The script I use below is sending the first of the two messages, but the second one never arrives. How can I solve this?
$transport = Swift_SmtpTransport::newInstance('smtp.mysite.nl', 25)
->setUsername('myusername')
->setPassword('mypassword')
;
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance()
// Set the content type
/* ->setContentType("text/html"); */
// Give the message a subject
->setSubject("mysubject")
// Set the From address with an associative array
->setFrom(array('email#email.com' => "emailer"))
// Set the To addresses with an associative array
->setTo(array('email#email.com' => "emailer"))
// Give it a body
->setBody('My message', 'text/html');
// Create the message
$message2 = Swift_Message::newInstance()
// Set the content type
/* ->setContentType("text/html"); */
// Give the message a subject
->setSubject("mysubject")
// Set the From address with an associative array
->setFrom(array('email#email.com' => "emailer"))
// Set the To addresses with an associative array
->setTo(array('email#email.com' => "emailer"))
// Give it a body
->setBody('My message', 'text/html');
$result = $mailer->send($message, $message2);
In short: $message is sent, $message2 is not sent. I DO NOT GET ANY ERRORS FROM THIS SCRIPT!
Try to use something like:
require_once 'lib/swift_required.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setBody('Here is the message itself');
// Send the message
$failedRecipients = array();
$numSent = 0;
$to = array('receiver#domain.org', 'other#domain.org' => 'A name');
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo(array($address => $name));
}
$numSent += $mailer->send($message, $failedRecipients);
}
printf("Sent %d messages\n", $numSent);
Such services usually have different methods of sending multiple emails.
Try sending it one bye one.
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('yourUsername')
->setPassword('yourPassword');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Your message')
->setFrom(array('enquiries#dtect.com' => 'Enquiry'))
->setTo(array('enquiries#dtect.com'))
->setBody("Body content");
$result = $mailer->send($message);
$mailer2 = Swift_Mailer::newInstance($transport);
$message2 = Swift_Message::newInstance('Dtect Report Portal - '.$typeOfEnquiry)
->setFrom(array('enquiries#dtect.com' => 'Enquiry'))
->setTo($emailAddress)
->setBody("Dear ".$name.","."\r\n".
"Thank you for contacting us"."\r\n".
"We will respond to your enquiry as soon as possible"."\r\n".
"Regards");
$result2 = $mailer2->send($message2);
Hope this help.

sending mail in magento

How to send email in magento writing an action in index controller?
my index controller;
public function postAction()
{
$post = $this->getRequest()->getPost();
if(!$post) exit;
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Please enter a valid email address. For example johndoe#domain.com.').'</div>';
exit;
}
$storeId = Mage::app()->getStore()->getStoreId();
$emailId = Mage::getStoreConfig(self::XML_PATH_SAMPLE_EMAIL_TEMPLATE);
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
->setReplyTo($post['email'])
->sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
if (!$mailTemplate->getSentSuccess()) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').'</div>';
exit;
}
$translate->setTranslateInline(true);
echo '<div class="success-msg">'.Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.').'</div>';
}
catch (Exception $e) {
$translate->setTranslateInline(true);
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').$e.'</div>';
exit;
}
}
is there any wrong..
please help me to out of this..
Thanks in advance..
Here's another way, if you don't need templates.
Call from a controller.
<?php
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('John Customer');
$mail->setToEmail('customer#email.com');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('yourstore#url.com');
$mail->setFromName("Your Name");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
$this->_redirect('');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
It looks like there are a few problems with the way you are calling sendTransactional(). First off, $templateId is not defined, it looks like you've actually stored the template id in $emailId. Also, $sender, $email, and $name are undefined. You can try something like this:
->sendTransactional($emailId, 'general', $post['email'], "Need a send to name here")
This is only going to work if you are getting a valid template id back from your call to getStoreConfig(). You'll also need to set the last name param correctly.
There could be other issues, but that's what I noticed with a quick glance anyway.
Finally i created a function for sending mail by using zend
public function sendMail()
{
$post = $this->getRequest()->getPost();
if ($post){
$random=rand(1234,2343);
$to_email = $this->getRequest()->getParam("email");
$to_name = 'Hello User';
$subject = ' Test Mail- CS';
$Body="Test Mail Code : ";
$sender_email = "sender#sender.com";
$sender_name = "sender name";
$mail = new Zend_Mail(); //class for mail
$mail->setBodyHtml($Body); //for sending message containing html code
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname); //can set cc
//$mail->addBCc($bcc, $bccname); //can set bcc
$mail->setSubject($subject);
$msg ='';
try {
if($mail->send())
{
$msg = true;
}
}
catch(Exception $ex) {
$msg = false;
//die("Error sending mail to $to,$error_msg");
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($msg));
}
}

Resources