How to compose mail in yii onclick on menu
To compose a mail in Yii and send it when a menu item is clicked, you can follow these steps:
Step 1: Create a mail composer
Create a new PHP class that will handle the mail composition. For example, create a file MailComposer.php
in the protected/components
directory:
<?php
class MailComposer extends CController {
public function composeMail($subject, $body, $fromEmail, $fromName, $toEmail, $toName) {
// Set the mail headers
$headers = 'From: '. $fromEmail. ' '. $fromName. "\r\n";
$headers.= 'Reply-To: '. $fromEmail. "\r\n";
$headers.= 'MIME-Version: 1.0'. "\r\n";
$headers.= 'Content-Type: text/plain; charset=UTF-8'. "\r\n";
// Set the mail body
$body = wordwrap($body, 70);
// Send the mail
$mail = new CPHPMailer();
$mail->IsSMTP();
$mail->Host = 'your_smtp_host';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->SetFrom($fromEmail, $fromName);
$mail->AddAddress($toEmail, $toName);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = $body;
$mail->Send();
}
}
Step 2: Create a menu item
Create a new menu item in your Yii application's main.php
file:
'menu' => array(
//...
array(
'label' => 'Compose Mail',
'url' => '#',
'items' => array(
array(
'label' => 'Compose',
'url' => '#',
'visible' => true,
'ajax' => array(
'type' => 'POST',
'url' => 'mail/compose',
'data' => array('subject' => '', 'body' => '', 'fromEmail' => '', 'fromName' => '', 'toEmail' => '', 'toName' => ''),
'success' => 'function(data) { alert("Mail sent!"); }',
),
),
),
),
//...
),
Step 3: Handle the menu item click
Create a new action in your MailController
to handle the menu item click:
public function actionCompose() {
$subject = $_POST['subject'];
$body = $_POST['body'];
$fromEmail = $_POST['fromEmail'];
$fromName = $_POST['fromName'];
$toEmail = $_POST['toEmail'];
$toName = $_POST['toName'];
$mailComposer = new MailComposer();
$mailComposer->composeMail($subject, $body, $fromEmail, $fromName, $toEmail, $toName);
// Return a success message
echo 'Mail sent!';
Yii::app()->end();
}
Step 4: Test the mail composition
Run your Yii application and click on the "Compose Mail" menu item. Fill in the required fields and click the "Compose" button. The mail should be sent successfully.
Note: Make sure to replace the placeholders (your_smtp_host
, your_smtp_username
, your_smtp_password
) with your actual SMTP server settings.