how to send email from localhost with php CodeIgniter

北慕城南 提交于 2019-12-06 16:07:05

Use PHPMailer. Its available here PHPMailer. You can use it like this:

public function send_mail()
    {
        require_once(APPPATH.'third_party/PHPMailer-master/PHPMailerAutoload.php');
        $mail = new PHPMailer();
        $mail->IsSMTP(); // we are going to use SMTP
        $mail->SMTPAuth   = true; // enabled SMTP authentication
        $mail->SMTPSecure = "ssl";  // prefix for secure protocol to connect to the server
        $mail->Host       = "smtp.gmail.com";      // setting GMail as our SMTP server
        $mail->Port       = 465;                   // SMTP port to connect to GMail
        $mail->Username   = "mail@gmail.com";  // user email address
        $mail->Password   = "password";            // password in GMail
        $mail->SetFrom('mail@gmail.com', 'Mail');  //Who is sending 
        $mail->isHTML(true);
        $mail->Subject    = "Mail Subject";
        $mail->Body      = '
            <html>
            <head>
                <title>Title</title>
            </head>
            <body>
            <h3>Heading</h3>
            <p>Message Body</p><br>
            <p>With Regards</p>
            <p>Your Name</p>
            </body>
            </html>
        ';
        $destino = receiver@gmail.com; // Who is addressed the email to
        $mail->AddAddress($destino, "Receiver");
        if(!$mail->Send()) {
            return false;
        } else {
            return true;
        }
    }

Remember to set access for less trusted apps in your gmail account

Rashmy

In your $config array, try this instead:

'smtp_host' => 'ssl://smtp.googlemail.com',

You can use Codeigniter Library to send email from localhost and live server as follows:

$localhosts = array(
    '::1',
    '127.0.0.1',
    'localhost'
);

$protocol = 'mail';
if (in_array($_SERVER['REMOTE_ADDR'], $localhosts)) {
    $protocol = 'smtp';
}

$config = array(
    'protocol' => $protocol,
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'Your-Email',
    'smtp_pass' => 'Your-Email-Password',
    'mailtype' => 'html',
    'starttls'  => true,
    'newline'   => "\r\n",
);

$this->load->library('email');
$this->email->initialize($config);
$this->email->from("From-Email");
$this->email->to("To-Email");
$this->email->subject("New user contacts");
$this->email->message($final_mail);
$flag = $this->email->send();

if($flag){
    echo "Email sent";
}else{
    echo "Email sending failed";
}

For more details refer to this article of Coderanks.com.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!