I'm trying to send email to selected users by nette mailer but it allways results with an InvalidStateException.
public function contactsEditorFormSucceeded($form, $values)
{
try {
$recipients = $values->recipients;
$mail = new Message;
$mail->setFrom($values->email)
->setSubject($values->subject)
->setBody($values->message);
foreach ($recipients as $recipient) {
$mail->addTo($recipient);
}
$mailer = new SendmailMailer;
$mailer->send($mail);
$this->flashMessage('Done.', self::MSG_SUCCESS);
$this->redirect('this');
} catch (InvalidStateException $ex) {
$this->flashMessage('Error', self::MSG_ERROR);
}
}
I'm using foreach to get multiple addTo() but it will not send the mails.
Message can not have multiple recipients. It is necessary to create a cycle and create so many messages about how many recipients are
public function contactsEditorFormSucceeded($form, $values)
{
try {
$recipients = $values->recipients;
foreach ($recipients as $recipient) {
$mail = new Message;
$mail->setFrom($values->email)
->setSubject($values->subject)
->setBody($values->message)
->addTo($recipient);
$mailer = new SendmailMailer;
$mailer->send($mail);
}
$this->flashMessage('Done.', self::MSG_SUCCESS);
$this->redirect('this');
} catch (InvalidStateException $ex) {
$this->flashMessage('Error', self::MSG_ERROR);
}
}
Related
I'm using sendgrid to send out html emails from a document system I'm building. When a file uploads sendgrid needs to email all those associated with that case. I have everything working for individual emails and I can customs the template I have saved but cant send the email to multiple recipients
I have generated an array of recipients
$email = array(j.bloggs#bloggs.com, j.doe#me.net, d.smith#smith.co.uk);
I want to pass this into my sendgrid email object to send to them all
private function send() {
$sg = new \SendGrid(self::$key);
$response = $sg->client->mail()->send()->post(self::$mail);
return $response->statusCode();
}
public function file_saved($file="", $case="") {
self::$from = new SendGrid\Email($this->fromName, $this->fromEmail);
self::$to = new SendGrid\Email($this->toName, $this->toEmail);
self::$content = new SendGrid\Content("text/html", "Hello, Email!");
self::$mail = new SendGrid\Mail(
self::$from,
$this->subject,
self::$to,
self::$content
);
$str = "<p>A file has been successfully uploaded to {$case->case_name} ({$case->case_code}).</p>
<br />
<p>{$file->file_name} - ".size($file->file_size)."</p>";
self::$mail->personalization[0]->addSubstitution("-name-", $this->toName);
self::$mail->personalization[0]->addSubstitution("-str-", $str);
self::$mail->personalization[0]->addSubstitution("-btn-", "Download File");
self::$mail->personalization[0]->addSubstitution("-url-", HTTP.BASE_URL.DS.'uploads'.DS.$file->file_path);
self::$mail->setTemplateId("2f845487-6243-4562-b6fb-022185b7fde7");
if (!$this->send() == 202) {
return false;
}
else {
return true;
}
}
I tried to use the personalization->to and pass that the array but get the error
Call to a member function to() on null in includes/classes/mail.php on line <b>82</b><br />
I just created a loop that went through each recipient and sent them an email, not as efficient as generating a multiple to: list but for now its working until I get a response from the sendgrid dev team
$this->email = array(j.bloggs#bloggs.com, j.doe#me.net, d.smith#smith.co.uk);
private function send() {
$sg = new \SendGrid(self::$key);
$response = $sg->client->mail()->send()->post(self::$mail);
return $response->statusCode();
}
public function file_saved($file="", $case="") {
$str = "<p>A file has been successfully uploaded to {$case->case_name} ({$case->case_code}).</p>
<br />
<p>{$file->file_name} - ".size($file->file_size)."</p>";
self::$from = new SendGrid\Email($this->fromName, $this->fromEmail);
self::$content = new SendGrid\Content("text/html", "Hello, Email!");
foreach($this->email as $email_addr) {
self::$to = new SendGrid\Email($this->toName, $email_addr);
self::$mail = new SendGrid\Mail(
self::$from,
$this->subject,
self::$to,
self::$content
);
self::$mail->personalization[0]->addSubstitution("-str-", $str);
self::$mail->personalization[0]->addSubstitution("-btn-", "Download File");
self::$mail->personalization[0]->addSubstitution("-url-", HTTP.BASE_URL.DS.'uploads'.DS.$file->file_path);
self::$mail->setTemplateId("2f845487-6243-4562-b6fb-022185b7fde7");
if (!$this->send() == 202) {
$response[$address] = false;
}
else {
$response[$address] = true;
}
}
return $response; // contains true/false for each email address if sent or not.
}
I have implement the gcm to send notification to my application and its really working perfect.
I am getting notification on device but issue is that I am getting logs detail may be in notification message instead of only human readable message that I am pushing.
Here is my code that I am using to send notification:
$gcmApiKey = GOOGLE_API_KEY;
$pushApi = new PushAPI();
$sender = new \PHP_GCM\Sender($gcmApiKey);
$message = new \PHP_GCM\Message("1", $messsageVal);
try {
$multicastResult = $sender->sendMulti($message, $deviceRegistrationId, 2);
$results = $multicastResult->getResults();
for ($i = 0; $i < count($deviceRegistrationId); $i++) {
$regId = $deviceRegistrationId[$i];
$result = $results[$i];
$messageId = $result->getMessageId();
if ($messageId != null) {
$canonicalRegId = $result->getCanonicalRegistrationId();
if ($canonicalRegId != null) {
// same device has more than on registration id: update it
}
} else {
$error = $result->getErrorCodeName();
if ($error == \PHP_GCM\Constants::$ERROR_NOT_REGISTERED) {
$pushApi->clearDeviceByDeviceId($regId);
}
}
}
} catch (\InvalidArgumentException $e) {
// $deviceRegistrationId was null
} catch (PHP_GCM\InvalidRequestException $e) {
// server returned HTTP code other than 200 or 503
} catch (\Exception $e) {
// message could not be sent
}
Here is the link of whole API that I am using. PHP_GCM
I try to google it but I didn't get anything to rectify this.
Any help will be appreciated.
You have to parse your response same as you parse a webservice response and show only the msg.
Try getting the message from the received intent using:
String msg=intent.getExtras().getString("msg");
Then show the message as :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.mipmap.app_icon)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle(context.getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
Try block for email sending is working, but it directly redirect to another page without sending mail. smtp setting are okay. This code was working perfectly but now nothing is happening.
try{ ..........................................//mail senting
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
//get customer details
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->getId();
$customer->getEmail();
//get general store details
$from_name = Mage::getStoreConfig('trans_email/ident_general/name');
$from_email = Mage::getStoreConfig('trans_email/ident_general/email');
$templateId=7;
$emailTemplate = Mage::getModel('core/email_template')->load($templateId);
//$emailTemplateVariables = array();
//$emailTemplateVariables[‘name′] = "$mh"";
$processedTemplate = $emailTemplate->getProcessedTemplate();
$mail=Mage::getModel('core/email');
$mail->setToName($customer->getId());
$mail->setToEmail($customer->getEmail());
$mail->setBody($processedTemplate);
$mail->setSubject("Upload Conformation ");
// print_r($mail);
//die;
$mail->setFromEmail($from_email);
$mail->setFromName($from_name);
$mail->setType('html');
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
}
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl().'bank-info/');
} catch (Exception $ex) {
Mage::getSingleton('core/session')->addError($ex->getMessage());
Mage::log($ex->getMessage());
Mage::getSingleton("supplierfrontendproductuploader/session")->setProductData($postData);
if($editMode) {
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . 'supplierfrontendproductuploader/product/edit/id/'.$postData['product_id']);
} else {
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getBaseUrl() . 'supplierfrontendproductuploader/product/create/');
}
i am trying to set html on the output of the email send by joomla. my file is located in the joomla core.
i know i have to add something like ->isHTML(true); but i do not know where and how.
here is the code:
class MailtoController extends JControllerLegacy
{
/**
* Show the form so that the user can send the link to someone.
*
* #return void
*
* #since 1.5
*/
public function mailto()
{
$session = JFactory::getSession();
$session->set('com_mailto.formtime', time());
$this->input->set('view', 'mailto');
$this->display();
}
public function send()
{
// Check for request forgeries
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$app = JFactory::getApplication();
$session = JFactory::getSession();
$timeout = $session->get('com_mailto.formtime', 0);
if ($timeout == 0 || time() - $timeout < 1)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
$SiteName = $app->get('sitename');
$link = MailtoHelper::validateHash($this->input->get('link', '', 'post'));
// Verify that this is a local link
if (!$link || !JUri::isInternal($link))
{
// Non-local url...
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
// An array of email headers we do not want to allow as input
$headers = array (
'Content-Type:',
'MIME-Version:',
'Content-Transfer-Encoding:',
'bcc:',
'cc:'
);
// An array of the input fields to scan for injected headers
$fields = array(
'mailto',
'sender',
'from',
'subject',
);
/*
* Here is the meat and potatoes of the header injection test. We
* iterate over the array of form input and check for header strings.
* If we find one, send an unauthorized header and die.
*/
foreach ($fields as $field)
{
foreach ($headers as $header)
{
if (strpos($_POST[$field], $header) !== false)
{
JError::raiseError(403, '');
}
}
}
/*
* Free up memory
*/
unset ($headers, $fields);
$email = $this->input->post->getString('mailto', '');
$sender = $this->input->post->getString('sender', '');
$from = $this->input->post->getString('from', '');
$subject_default = JText::sprintf('COM_MAILTO_SENT_BY', $sender);
$subject = $this->input->post->getString('subject', $subject_default);
// Check for a valid to address
$error = false;
if (!$email || !JMailHelper::isEmailAddress($email))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $email);
JError::raiseWarning(0, $error);
}
// Check for a valid from address
if (!$from || !JMailHelper::isEmailAddress($from))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $from);
JError::raiseWarning(0, $error);
}
if ($error)
{
return $this->mailto();
}
// Build the message to send
$msg = JText::_('COM_MAILTO_EMAIL_MSG');
$link = $link;
//$body = sprintf($msg, $SiteName, $sender, $from, $link);
$body = "<p>Hello Test F,</p><br/><p>Thank you for registering at Deals&offers. Your account is created and activated.</p><br/>You may login to ".$SiteName." using the following username and password:</br><p>Username: ".$sender."</p><p>Password: ".$from."/p><br/><p><b>Note:</b> It is recomended to change your password after first login. ".$link."</p>";
// Clean the email data
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
// To send we need to use punycode.
$from = JStringPunycode::emailToPunycode($from);
$from = JMailHelper::cleanAddress($from);
$email = JStringPunycode::emailToPunycode($email);
// Send the email
if (JFactory::getMailer()->sendMail($from, $sender, $email, $subject, $body) !== true)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
JFactory::getApplication()->enqueueMessage('ok!', '');
$this->input->set('view', 'sent');
$this->display();
}
}
thank you very much
you can add before body or between subject and body . however, it must be before the submit command !!
here is an example of PhpMailler firstly, you need to call the class like this and you can use it
$this->mail= new PHPMailer();
$this->mail->IsSMTP();
$this->mailIsHTML(true);
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
however if the function is static also you call the function in same class
you can call the function by sef command
self::mailIsHTML(true)
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.)