Sending multiple messages with swiftmailer - PHP - swiftmailer

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.

Related

PHP - EWS, change organizer to room mailbox email

I've been using php-ews for a month, i able to make a meeting but i want the organizer is the room email / room name that i attend the meeting
so for example, i create a meeting at 8:00am - 10:00am at room1 (room1#mydomain.com), i want the organizer is the room email (room1#mydomain.com) / room name (room1)
i know i can do this in the office 365 (login with my credential ->choose open another mailbox -> choose room1#mydomain.com), but i want to do this via php-ews
i already set the resource mailbox, mailbox delegation property to my login credential
is it possible to change the organizer name to room name / room email??
my basic code:
$host = $selected_exchange->exchange_host;
$username = $exchange_email;
$password = $exchange_password;
$version = $selected_exchange->exchange_version;
$timezone = 'SE Asia Standard Time';
$client = new Client($host, $username, $password, $version);
$client->setTimezone($timezone);
$start = new DateTime($booking_date . $booking_time_start . ":00");
$end = new DateTime($booking_date . $booking_time_end);
$guests = array(
array(
'name' => $room->exchange_room_name,
'email' => $room->exchange_room_email,
)
);
// Set connection information.
$request = new CreateItemType();
$request->SendMeetingInvitations = 'SendOnlyToAll';
//CalendarItemCreateOrDeleteOperationType::SEND_ONLY_TO_ALL;
$request->Items = new NonEmptyArrayOfAllItemsType();
// Build the event to be added.
$event = new CalendarItemType();
$event->RequiredAttendees = new NonEmptyArrayOfAttendeesType();
$event->Start = $start->format('c');
$event->End = $end->format('c');
$event->Subject = $meeting_title;
$event->Location = $room->exchange_room_name;
// Set the event body.
$event->Body = new BodyType();
$event->Body->_ = $special_request . " Meeting Created By: ";
$event->Body->BodyType = 'Text'; //BodyTypeType::TEXT;
// Iterate over the guests, adding each as an attendee to the request.
foreach ($guests as $guest) {
$attendee = new AttendeeType();
$attendee->Mailbox = new EmailAddressType();
$attendee->Mailbox->EmailAddress = $guest['email'];
$attendee->Mailbox->Name = $guest['name'];
$attendee->Mailbox->RoutingType = 'SMTP'; //RoutingType::SMTP;
$event->RequiredAttendees->Attendee[] = $attendee;
}
try
{
// Add the event to the request. You could add multiple events to create more
// than one in a single request.
$request->Items->CalendarItem[] = $event;
$response = $client->CreateItem($request);
// Iterate over the results, printing any error messages or event ids.
$response_messages = $response->ResponseMessages->CreateItemResponseMessage;
foreach ($response_messages as $response_message) {
// Make sure the request succeeded.
if ($response_message->ResponseClass != ResponseClassType::SUCCESS) {
$code = $response_message->ResponseCode;
$message = $response_message->MessageText;
//fwrite(STDERR, "Event failed to create with \"$code: $message\"\n");
$result = array('ok' => 0, 'message' => $message);
continue;
}
// Iterate over the created events, printing the id for each.
foreach ($response_message->Items->CalendarItem as $item) {
$id = $item->ItemId->Id;
//fwrite(STDOUT, "Created event $id\n");
$result = array('ok' => 1, 'message' => 'Success Added To Calendar');
}
}
}
catch(Exception $e)
{
$result = array('ok' => 0, 'message' => $message);
}
I recently had to do this same thing. When I was searching, I found the answer within the Exchange SDK Docs :
https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2007/bb856541%28v%3dexchg.80%29
With only a few changes, I was able to make it work on the php-ews structure.
Basically you make the room as a distinguished folder and use it as the saved item folder id. The person who is logged in as the user must have Delegate access to the room, and it will automatically send the request from the user on behalf of the room, and the room will be the organizer.
// Set connection information with save copy so that it saves to the folder
$request = new CreateItemType();
$request->MessageDisposition = MessageDispositionType::SEND_AND_SAVE_COPY;
$request->SendMeetingInvitations = CalendarItemCreateOrDeleteOperationType::SEND_TO_ALL_AND_SAVE_COPY;
// Add the Room as the target saved item folder (user must have delagate access to the room)
$roomFolder = new DistinguishedFolderIdType();
$roomFolder->Id = DistinguishedFolderIdNameType::CALENDAR;
$roomFolder->Mailbox = new EmailAddressType();
$roomFolder->Mailbox->EmailAddress = $room->exchange_room_email;
$roomFolder->Mailbox->Name = $room->exchange_room_name;
$target = new TargetFolderIdType();
$target->DistinguishedFolderId = $roomFolder;
$request->SavedItemFolderId = $target;
$request->Items = new NonEmptyArrayOfAllItemsType();

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;
}

JMail usage for cutsom component programming

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();

How to use the Email template in Magento

I develop my store in magento community edition 1.5.0.1. I need a Email template that content will be editable by admin. I create a email template through admin "Transactional Emails". Now I need to access and use that email from my custom module. How do I get it?, you have any idea let me know.
This should do it.
public function sendTransactionalEmail() {
// Transactional Email Template's ID
$templateId = 1;
// Set sender information
$senderName = Mage::getStoreConfig('trans_email/ident_support/name');
$senderEmail = Mage::getStoreConfig('trans_email/ident_support/email');
$sender = array('name' => $senderName,
'email' => $senderEmail);
// Set recepient information
$recepientEmail = 'john#example.com';
$recepientName = 'John Doe';
// Get Store ID
$storeId = Mage::app()->getStore()->getId();
// Set variables that can be used in email template
$vars = array('customerName' => 'customer#example.com',
'customerEmail' => 'Mr. Nil Cust');
$translate = Mage::getSingleton('core/translate');
// Send Transactional Email
Mage::getModel('core/email_template')
->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $vars, $storeId);
$translate->setTranslateInline(true);
}

Resources