How to add setCc in yii2 mailer?
The shortfall to the above answers, particularly for newcomers, is that there is no mention as to how the value in the inputbox in the view is converted to the array as mentioned above. Noteworthily, a list of email addresses in an inputbox separated by a comma is not an array but a list. And a single value is not a list. So how can we capture both possible single values and multiple values:
Here is one way, with validation dynamically included in the controller as opposed to validation by means of a model, to convert the list of email addresses in the inputbox to an array whether the inputbox has one item only, or more than one item.
In your Controller:
//You can use the EmailValidator to validate each
//individual post from the view. In my case my
//cc inputbox has a name = "cc" and id = "cc"
use yii\validators\EmailValidator;
//Assuming your view stresses separation of fields
//with ONLY a comma ..as tip to inputbox.
public function emailinvoice() {
$validator = new EmailValidator([
'enableIDN'=>true,
'checkDNS'=>true
]);
//if getting value from view directly WITHOUT a model: id and name of inputbox is 'cc'
$cc = Yii::$app->request->post('cc');
//if getting value from model: field is called 'email_2'
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$cc = $model->email_2;
//catch multiple addresses by building an array
//as mentioned above
$array = [];
//the field is not empty => single address, or there is a separator comma in it => multiple addresses.
//You can add more validators here ie || (strpos($cc, ';')
if (!empty($cc)||(strpos($cc, ','))){
//remove comma
$cc = explode(',', $cc);
//after explode cc is an array.
//so $cc[0] = 'name@domain.com'
//and $cc[1] = ' name2@domain.com'
//Note the space before the second
//element which you will have to remove.
//Each array component could have a
//space before it especially the second
//element so trim spaces for all items
//in new array
$i = 0;
foreach ($cc as $address) {
//remove the potential spaces
$address = ltrim(rtrim($address));
if ($validator->validate($address)) {
//include in new array
$array[$i] = $address;
}
else {
Yii::$app->session->setFlash('danger', 'cc error'.$i);
}
$i+=1;
}
$send->setCc($array);
}
}