Sending multiple emails in YII using YiiMail extension - php

I am using YiiMail Extension to send mails.
I have my default contact.php file as my view. I am able to send mails for individuals but multiple emails are not allowed here.
mycontroller-
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$message = new YiiMailMessage;
$message->Body=$_POST['body'];
$message->subject = $_POST['subject']
$message->addTo($_POST['email']);
$message->from = "frommail#gmail.com";
if(Yii::app()->mail->send($message) )
echo 'mail sent';
else
echo 'error while sending email';
}
}
I have tried the following too-
foreach ($model as $value)
{
$message->addTo($model[$value]);
}
It does not accept multiple email id's. How can this be resolved?

I have checked code in Yii Mailer. They haven't given such facility. If you like to achieve then you need to extend Yii Mail. It's ultimately useless because looping in your new extended class OR looping in your controller are same.
Regards...

You can pass multiple recipients mail ids as array
$recipients = array('test1#example.com','test2#example.com','test3#example.com');
$message->addTo('test1#example.com');
foreach($recipients as $email) {
$mail->AddBCC($email); // if you want more than one email
}

Related

How to send email to multiple recipients laravel

I am trying to create an application where one of the features is to send email to multiple addresses, and it has not been easy. I used a foreach loop, but whenever an error occurs, most especially if the recipient mail address is not valid the application stops.
This is my code
public function sendemails(Request $request){
$email = $this->emailSetUp($request);
$emails = $email->recipients;
foreach ($emails as $value) {
try{
$mail = Mail::to($value)->send(new SendEmail($email));
}catch( \Swift_RfcComplianceException $e){
$pattern = '/[a-z0-9_\-\+\.]+#[a-z0-9\-]+\.([a-z]{2,4})(?:\.[a-z]{2})?/i';
preg_match_all($pattern, $e, $matches);
$match = implode(',',$matches[0]);
$mail_t_del = Email::where('email','LIKE', '%'.$match)->first();
$mail_t_del->delete();
Log::info($match .' '. 'deleted');
$email = $this->emailSetUp($request);
$mail = Mail::send(new SendEmail($email));
}
}
}
How can i
Send the message to multiple recipients and also make it fail proof, by continuing after the exception has been thrown.
How can i track the progress of the application i.e know the emails that has been sent and the on that has been rejected.
You can pass an array of emails.
see here for details
https://laravel.com/api/5.5/Illuminate/Contracts/Mail/Mailer.html#method_to
Also I suggest that you create a custom request to check to make sure that emails are valid before processing.
You can see how to do that here:
https://laravel.com/docs/5.7/requests
- Send the message to multiple recipients
pass all the emails in your mail class
Example:
Mail::to($users)->send(new SendEmail($yourData));
put your codes in try catch
so that you can ignore exception and continue to send other mails
- Track the progress
If you want to get which mails are sent or not
then handle it on catch statement exception and log it in file or DB
To send an email to multiple recipients without displaying the sent email to all recipients, try this:
This method will loop through the emails supplied for form or database. in this example the user IDs come from form requests, then, email is retrieved from the database for selected users.
foreach($request->get_emails as $i => $a){
$user = User::find($a);
Mail::send('emails.template', ['name' => $user['name'], 'body' => $request->body], function ($m) use($user) {
$m->from('info#example.com', 'Sender Name');
$m->to($user['email'], $user['name'])->subject('this is the subject');
});
}
Also, you may choose to display emails to all recipient. To do that, try:
$emails = ['eamil1#example.com', 'email2#example.com','email3#example.com'];
Mail::send('emails.template', [], function($m) use ($emails)
{
$m->to($emails)->subject('This is the email subject');
});

Why is the email is not send in this code? Magento

I am trying to send a email for a user when he fill a form and click the submit.I have created a controller in Magento and included the following code
public function sendMailAction(){
$html="put your html content hereblah blah";
$mail = Mage::getModel('core/email');
$mail->setToName('Your Name');
$mail->setToEmail('sadeeenadeee#gmail.com');
$mail->setBody('Mail Text / Mail Content');
$mail->setSubject('Mail Subject');
$mail->setFromEmail('Sender Mail Id');
$mail->setFromName("Msg to Show on Subject");
$mail->setType('html');// YOu can use Html or text as Mail format
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('');
}
}
This is the function I am planning to use to send the email.Above controller function is called for the click of the submit button.
Then I configured the outgoing SMTP email in Magento admin panel.
System > Configuration-> Mail Sending Settings
I followed the above path and added the HOST and PORT in the Mail Sending Settings and saved the config.HOST and PORT are obtained from the email service provider.But when a user fills the form and click the submit,rather than sending a email browser tries to launch a app saying that,
THIS LINK NEEDS TO BE OPEN WITH AN APPLICATION
Can someone help me please?
I AM WORKING ON A HOSTED SITE
$emailTemplateVariables = array();
$EmailSenderName="Email Sender Name";
$EmailId="semder Email";
$emailTemplateVariables['key1'] = "data1";
$emailTemplateVariables['key2'] = "data2";
/* sent mail to //recepient */
$recipientEmail="abcd#xyz.com";
$sender = Array('name' => $EmailSenderName,
'email' => $EmailId);
$emailName = 'Email Name';
$translate = Mage::getSingleton('core/translate');
$emailTemplate = Mage::getModel('core/email_template')
->loadDefault('Any_email_template');
$emailTemplate->setSenderName($EmailSenderName)
->setSenderEmail($EmailId)
->setTemplateSubject($emailName);
$emailstatus=$emailTemplate->send($recipientEmail, $emailName, $emailTemplateVariables);
$translate->setTranslateInline(true);
if($emailstatus) {
//email send successfully
}
else {
//something went wrong
}
Please confirm that any mails in que for that enter the terminal command
mailq
$emailTemplate = Mage::getModel('core/email_template')->load(1); //1 is Transactional Emails id
if you want to try default the above

A simple email client/contact form is returning a "5.5.4 Invalid Domain Error" and I have exhausted all my resources attempting to solve it

I've posted this question twice in the last two days and I have really run dry of solutions. I'm creating a very simple comment box that when filled out sends the comment in an email to my company's safety department. I have been receiving this 5.5.4 Invalid Domain Error for the last couple days.
It's SMTP and TLS. The port and server name is correct. The server allows for anonymous emails, and does not validate. I'm using the Swiftmailer library so I shouldn't need to script a ELHO/HELO. The only property of the email that's not defined/hard coded is the body of the message. This is the code for my controller (index.php).
// Initialize Swiftmailer Library
require_once("./swiftmailer/lib/swift_required.php");
// Class that contains the information of the email that will be sent (from, to, etc.)
require_once("./classes/EmailParts.php");
// The class that "breaks" the data sent with the HTML form to a more "usable" format.
require_once("./classes/ContactForm.php");
// =====================
// Main Configuration
// =====================
define("EMAIL_SUBJECT", "Safety Concerns");
define("EMAIL_TO", "safetydepartment#company.com");
define("EMAIL_FROM", "safetydepartment#company.com");
// SMTP Configuration
define("SMTP_SERVER", 'exchange.company.local');
define("SMTP_PORT", 25);
function main($contactForm) {
// Checks if something was sent to the contact form, if not, do nothing
if (!$contactForm->isDataSent()) {
return;
}
// Validates the contact form and checks for errors
$contactForm->validate();
$errors = array();
// If the contact form is not valid:
if (!$contactForm->isValid()) {
// gets the error in the array $errors
$errors = $contactForm->getErrors();
} else {
// If the contact form is valid:
try {
// send the email created with the contact form
$result = sendEmail($contactForm);
// after the email is sent, redirect and "die".
// We redirect to prevent refreshing the page which would resend the form
header("Location: ./success.php");
die();
} catch (Exception $e) {
// an error occured while sending the email.
// Log the error and add an error message to display to the user.
error_log('An error happened while sending email contact form: ' . $e->getMessage());
$errors['oops'] = 'Ooops! an error occured while sending your email! Please try again later!';
}
}
return $errors;
}
// Sends the email based on the information contained in the contact form
function sendEmail($contactForm) {
// Email part will create the email information needed to send an email based on
// what was inserted inside the contact form
$emailParts = new EmailParts($contactForm);
// This is the part where we initialize Swiftmailer with
// all the info initialized by the EmailParts class
$emailMessage = Swift_Message::newInstance()
->setSubject($emailParts->getSubject())
->setFrom($emailParts->getFrom())
->setTo($emailParts->getTo())
->setBody($emailParts->getBodyMessage());
// Another Swiftmailer configuration..
$transport = Swift_SmtpTransport::newInstance(SMTP_SERVER, SMTP_PORT, 'tls');
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($emailMessage);
return $result;
}
// Initialize the ContactForm with the information of the form and the possible uploaded file.
$contactForm = new ContactForm($_POST, $_FILES);
// Call the "main" method. It will return a list of errors.
$errors = main($contactForm);
// Call the "contactForm" view to display the HTML contact form.
require_once("./views/contactForm.php");
I've posted the entirety of my code at Dropbox. There's not much, but I think the problem must lie in the Index.

Sending html email in Codeigniter

I am sending a template html in codeigniter and in fact my email is working perfectly fine.
My problem is how i send a template of html to the email. I got an error because of the variables passed to.
public function send_email_accountability($C11, $C4, $C8,$C12)
{
date_default_timezone_set('Asia/Manila');
$message = $this->load->view('sample_html',$data,TRUE);
$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->from('noreply#email.com', 'EMAIL');
$this->email->to($C11);
$this->email->subject('Accountability for'. $C12);
$this->email->message($message);
}
I receive the email but inside the email is php error because the $data cannot be passed to. I looked at other stackoverflow problems and it didn't help my problem.
public function send_email_accountability($C11, $C4, $C8,$C12)
{
date_default_timezone_set('Asia/Manila');
$this->load->library('email');
$data['title']='HELLO WORLD';
$this->email->from('noreply#email.com', 'EMAIL');
$this->email->to($C11);
$this->email->subject('Accountability for'. $C12);
$this->email->set_mailtype("html");
$msg = $this->load->view('sample_html',$data,TRUE);
$this->email->message($msg);
$this->email->send();
}
Try this one
use PHPmailer. It will help You. I also use it. You can get all information about PHPmailer from here
you are using a data array ($data) to the view, but no values is assigned to it,
just assign any value to array to avoid the error,
$data['logo_img'] = 'images/logo.png'; // add this line before loading the view
This logo image is located as $logo_img in the view sample_html...

'To' address being added twice while using PHPmailer

I am using PHPmailer to send mails. However, the mail is being sent to each user twice. Below is the screen-shot of a test mail.
The following is my code :
<?php
##REQUIRED FUNCTION
function send_mail_to($receiver, $msg)
{
$subject="[ TNP Update ] - Do you like the new look ?";
#Grab the PHPmailer class
require_once('./lib/phpmailer/phpmailer.inc.php');
#Create object
$mailer = new PHPmailer(); //Instantiate class
$mailer->From="tnp#aakashbhowmick.in";
$mailer->FromName="TNP Mailer";
$mailer->IsHTML(true);
$mailer->Subject = $subject;
$mailer->Body = $msg;
$mailer->AddAddress($receiver);
#Send the email
set_time_limit(300);
$mailer->Send();
} //End of send_mail_to()
###### THE WORKING CODE ######
#Only authorised access is allowed.
if($_POST['signature']=="some-secret-signature-here"){
$msg1=urldecode($_POST['text']);
# Formatting the message a little
$msg1=str_replace("#c0c0c0","#EAE99A",$msg1);
$msg1=str_replace("<td","<td style='font-family:Trebuchet MS,Verdana,arial'; ",$msg1);
#Start sending mails. Some lines commented for testing purpose
//include("connection.php");
//$result=mysql_query("SELECT * FROM subscribers");
$subscriber=array('id'=>'1','email'=>'aakashrocks#gmail.com','active'=>'1');
//while($subscriber=mysql_fetch_array($result)){
if($subscriber['active']==1){
$body="Some text";
send_mail_to($subscriber['email'], $body);
} #End-of-if
//} #End-of-while
} ##End of if
?>
I had the same problem, for me solution was to change
$mailer->isSMTP();
to
$mailer->Mailer = 'smtp';
So, try to use $mailer->Mailer.
May be there is a page refresh and hence multiple execution - Make sure the mail method is called only once by the browser for each reciever. To make sure, you could set a session variable upon sending and go into the send part only if session is not set.
if(!isset($_SESSION[$reciever]))
{
$_SESSION[$reciever] = 1;
\\mail code here
}
else{
echo "doing it more than once";
}
Also you can set $mailer->$SingleTo to true, so you would know if its multiple execution or single. You could also send the timestamp with the email for more debugging.
I had the same problem but using the SMTP connection.
I still don't know why but it happens when your recipient doesn't have a name.
So, instead of
$mailer->AddAddress($receiver);
Do
$mailer->AddAddress($receiver, 'Receiver name');
I hope it helps.
I was experiencing the same problem. In my case changing mail systems did the trick.
By default, phpMailer sends out email using Mail. Once I told it to use Sendmail instead, I stopped getting the duplicate address.
$email = new phpmailer;
$email->mailer = "sendmail";

Categories