I'm trying to send an email in codeigniter via my Gmail account. My current code looks like this:
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'me#gmail.com',
'smtp_pass' => 'my_gmail_password',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('me#gmail.com', 'Me');
$this->email->to("me#gmail.com");
$this->email->subject('A test email from CodeIgniter using Gmail');
$this->email->message("A test email from CodeIgniter using Gmail");
$this->email->send();
However, this gives me the following errors:
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Connection timed out)
Filename: libraries/Email.php
Message: fwrite(): supplied argument is not a valid stream resource
Message: fgets(): supplied argument is not a valid stream resource
Any help to resolve this issue would be much appreciated! Thanks!
Note: I can assure you that my Gmail email & password are correct
The error means you cannot connect the the SMTP address you've entered.
you should use: smtp.gmail.com
Check following link for reference:
http://mail.google.com/support/bin/answer.py?answer=13287
You could download a nice little sparks package by "Shawn McCool" that utilizes "Swift-Mailer".
Check out his site for install instructions
Here is my configuration for sending out email's using a DRY approach(PHP 5.3.0 required!).
Config
|--mailer[dot]php
$config['swift_email_server'] = 'ssl://smtp.googlemail.com';
$config['swift_email_port'] = 465;
$config['swift_email_username'] = '######';
$config['swift_email_password'] = '######';
Libarary
|--MY_Email
class MY_Email extends CI_Email {
public function __construct(){
parent::__construct();
}
/**
* =========================================================================
* Parse's html email templates - initalised via swift-mailer
*
* #param mixed $data
* #param string $template
* #return html
*
* =========================================================================
*/
public function send_mail($data, $template){
//Anonymous functions are available since PHP 5.3.0
$callback = function ($matches) use ($data){
return ( isset($data[$matches[1]]) )
? $data[$matches[1]]
: $matches[0];
};
//Finds any matches in brackets [] and replaces them with data passed via callback
return preg_replace_callback(
'/\[(.*?)\]/',
$callback,
read_file(EMAIL_TEMPLATES . $template));
}
}
Email templates location defined in index.php
define('EMAIL_TEMPLATES', 'emailtemplates');
Controller
|--MY_Controller
class MY_Controller extends MX_Controller{
protected $user;
protected $swiftMailer = NULL;
public function __construct(){
parent::__construct();
$this->user = ($this->session->userdata('uid'))
? Member::find($this->session->userdata('uid')) : array();
$this->setup_profile();
$this->form_validation->set_error_delimiters('<p class="form-error">', '</p>');
}
public function setup_profile(){
$sections = array(
'config' => FALSE,
'http_headers' => FALSE,
'queries' => FALSE,
'memory_usage' => FALSE
);
$this->output->set_profiler_sections($sections);
if(ENVIRONMENT === 'development'){
$this->output->enable_profiler(TRUE);
}
}
protected function prep_email($data, $template){
$message =
Swift_Message::newInstance('Type your heading here...')
->setFrom($data['email_address'])
->setTo(array($this->config->item('primary_email'), $data['email_address']))
->setBody( $this->email->send_mail($data, $template))
->setContentType('text/html');
return ( $this->swiftMailer->send($message) );
}
}
Module
|--services // simple test module
public function arrange() {
$config = array(
array('field'=>'service', 'label'=>'Service', 'rules'=>'trim|required|max_lenght[128]'),
array('field'=>'num', 'label'=>'Numer of Sessions', 'rules'=>'trim|required|numeric'),
array('field'=>'request_date', 'label'=>'Request_date', 'rules'=>'trim|required'),
array('field'=>'note', 'label'=>'Note', 'rules'=>'trim|max_lenght[500]')
);
$this->form_validation->CI =& $this;
$this->form_validation->set_rules($config);
if($this->form_validation->run($this)){
$service = Service::find($this->input->post('service'));
if((int)$this->input->post('num') > 1){
$potential = ( $this->input->post('num') * $service->price );
}else{
$potential = $this->input->post('num');
}
$insert = array(
'service_id' => $this->input->post('service'),
'num' => $this->input->post('num'),
'request_date' => $this->input->post('request_date'),
'note' => serialize( $this->input->post('note') ),
'potential_income' => $potential,
'member_id' => $this->user->id,
'status' => 'pending'
);
$emaildata = array(
'service' => $service->slug,
'num' => $insert['num'],
'request_date' => $insert['request_date'],
'note' => $insert['note'],
'potential_income' => $potential,
'email_address' => $this->user->email_address,
'status' => 'pending',
'fullname' => $this->user->firstname . ' ' . $this->user->surname,
'message_sent' => date('M d h:iA'),
'site_link' => ''
);
if(Meeting::create($insert)){
if(parent::prep_email($emaildata, 'request_meeting[dot]html')){
$this->session->set_flashdata('success' ,'Request has been sent! You will recieve an email shortly from Paul');
//redirect('/');
}else{
$this->session->set_flashdata('error', 'Email service seems to be down at the moment');
//redirect('/');
}
}else{
$this->session->set_flashdata('error', 'Unable to request meeting at this time');
//redirect('/');
}
}else{
$this->meetings_form();
}
Hope this helps!
Related
why is my attempt to send the email unsuccessful, I can't see the error, all I get is the http status code 303 See More
In my opinion, what I'm doing is in accordance with the official documentation https://codeigniter.com/userguide3/libraries/email.html
the result i expect is an email sent
Can anyone help me?
, How can I solve this?
config/email.php
$config['settings'] = array(
'smtp_host' => 'smtp.mailtrap.io',
'smtp_port' => '2525',
'smtp_user' => '9cf16dcde1asdasde5f8',
'smtp_pass' => '079205e1asdasd26bf43',
'from_email' => 'no-reply#test.com',
'from_name' => 'Test',
'protocol' => 'smtp',
'smtp_crypto' => 'tls',
'mailtype' => 'html',
'charset' => 'utf-8',
'newline' => "\r\n",
'crlf' => "\r\n",
);
libraries/Ah_Email.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Ah_Email {
public function __construct()
{
$CI =& get_instance();
$CI->load->config('email', true);
$this->configs = $CI->config->config['email'];
$CI->load->library('email');
$this->email = $CI->email;
}
public function send($email_to, $subject, $template, $template_vars = array(), $settings = array())
{
$settings = array_merge(
$this->configs['settings'],
$settings
);
$this->email->initialize($settings);
$this->email->from($settings['from_email'], $settings['from_name']);
if (isset($settings['send_email']) && $settings['send_email']) {
$this->email->to($email_to);
}
$CI =& get_instance();
$this->email->subject($subject);
$this->email->message($CI->load->view('emails/' . $template, $template_vars, true));
$res = $this->email->send();
return $res;
}
}
My Controller
public function SendMail() {
$this->load->library('ah_email', 'ah_email');
$send = $this->ah_email->send('receiver#gmail.com', 'Informasi Kode OTP Akun Kamu', 'example', array(
'username' => 'Ndo Malau',
'message' => 'Hello World',
'mailtype' => 'text',
));
if($send) {
$result = redirect(base_url('Systems/Users/index/'), $this->session->set_flashdata('succ_msg', 'success, email has been sending!'));
} else {
$result = redirect(base_url('Systems/Users/index/'), $this->session->set_flashdata('err_msg', 'failed, error while email sending'));
}
return $result;
}
<?php
class SendEmail extends Controller
{
function SendEmail()
{
parent::Controller();
$this->load->library('email'); // load the library
}
function index()
{
$this->sendEmail();
}
public function sendEmail()
{
// Email configuration
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com.',
'smtp_port' => 465,
'smtp_user' => 'xxxx', // change it to yours
'smtp_pass' => 'xxxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from('xxxx', "Admin Team");
$this->email->to("xxxx");
$this->email->cc("xxxx");
$this->email->subject("This is test subject line");
$this->email->message("Mail sent test message...");
$data['message'] = "Sorry Unable to send email...";
if ($this->email->send()) {
$data['message'] = "Mail sent...";
}
// forward to index page
$this->load->view('index', $data);
}
}
?>
I get an error - I am doing it in codeigniter PHP Error was encountered
Severity: Compile Error
Message: Cannot redeclare SendEmail::sendEmail()
Filename: controllers/SendEmail.php
Line Number: 16
Backtrace:
Controller code
<?php
class SendEmail extends Controller
{
function __construct()
{
parent::__construct();
$this->load->library('email'); // load the library
}
function index()
{
$this->sendEmail();
}
public function sendEmail()
{
// Email configuration
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com.',
'smtp_port' => 465,
'smtp_user' => 'xxxx', // change it to yours
'smtp_pass' => 'xxxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from('xxxx', "Admin Team");
$this->email->to("xxxx");
$this->email->cc("xxxx");
$this->email->subject("This is test subject line");
$this->email->message("Mail sent test message...");
$data['message'] = "Sorry Unable to send email...";
if ($this->email->send()) {
$data['message'] = "Mail sent...";
}
// forward to index page
$this->load->view('index', $data);
}
}
?>
I'm trying to make my library to send email.
In my controller I set up as:
$this->load->library('MY_Email'); // My library has been loaded
File MY_Email.php
class MY_Email {
public $ci;
public $config;
public $email;
public function __construct () {
$ci = &get_instance();
$ci->load->config('email');
$this->config = array(
'protocol' => $ci->config->item('email_protocol'),
'smtp_host' => $ci->config->item('email_smtp_host'),
'smtp_port' => $ci->config->item('email_smtp_port'),
'smtp_timeout' => $ci->config->item('email_smtp_timeout'),
'smtp_user' => $ci->config->item('email_smtp_user'),
'smtp_pass' => $ci->config->item('email_smtp_pass'),
'charset' => $ci->config->item('email_charset'),
'mailtype' => $ci->config->item('email_mailtype'),
'validation' => $ci->config->item('email_validation')
);
$ci->load->library('email', $this->config);
/*This line print `Undefined property: Controller::$email` and result is NULL*/
var_dump($ci->email); die;
}
}
What is my wrong?
Thanks for any helps
Have you any idea how to control the queue of Mandrill send emails in PHP ?
Well, I'm using Symfony as a Framework, & this is my send function in the Mandrill class :
public function sendMandrill()
{
$listTo = array();
foreach ($this->contacts as $contact)
{
$listTo[] = [
'name' => $contact->getFname(),
'email' => $contact->getEmail()
];
}
var_dump($listTo);
$email = array(
'html' => $this->message->getBodyHtml(),
'text' => $this->message->getBodyText(),
'subject' => $this->message->getSubject(),
'from_email' => $this->apiDom,
'from_name' => $this->message->getFromName(),
'to' => $listTo,
"preserve_recipients"=> false,
);
$this->senderAPI = new \Mandrill("$this->apiKey");
return $this->senderAPI->messages->send($email);
}
Now, I want to create a function so I can pause the sending for a while so I can change such things, then resume it whenever I want or may be to stop it at all !
which mean there will be 3 functions as following :
public function pauseMandrill()
{
...
}
public function resumeMandrill()
{
...
}
public function stopMandrill()
{
...
}
I need help to figure out how to set the reply-to field in app/config/mail.php. I'm using Laravel 4 and it's not working. This is my app/config/mail.php:
<?php
return array(
'driver' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from' => [
'address' => 'sender#domain.com',
'name' => 'E-mail 1'
],
'reply-to' => [
'address' => 'replyto#domain.com',
'name' => 'E-mail 2'
],
'encryption' => 'tls',
'username' => 'sender#domain.com',
'password' => 'pwd',
'pretend' => false,
);
Pretty sure it doesn't work this way. You can set the "From" header in the config file, but everything else is passed during the send:
Mail::send('emails.welcome', $data, function($message)
{
$message->to('foo#example.com', 'John Smith')
->replyTo('reply#example.com', 'Reply Guy')
->subject('Welcome!');
});
FWIW, the $message passed to the callback is an instance of Illuminate\Mail\Message, so there are various methods you can call on it:
->from($address, $name = null)
->sender($address, $name = null)
->returnPath($address)
->to($address, $name = null)
->cc($address, $name = null)
->bcc($address, $name = null)
->replyTo($address, $name = null)
->subject($subject)
->priority($level)
->attach($file, array $options = array())
->attachData($data, $name, array $options = array())
->embed($file)
->embedData($data, $name, $contentType = null)
Plus, there is a magic __call method, so you can run any method that you would normally run on the underlying SwiftMailer class.
It's possible since Laravel 5.3 to add a global reply. In your config/mail.php file add the following:
'reply_to' => [
'address' => 'info#xxxxx.com',
'name' => 'Reply to name',
],
I'm using mailable and in my App\Mail\NewUserRegistered::class on the build function I'm doing this,
public function build()
{
return $this->replyTo('email', $name = 'name')
->markdown('emails.admin_suggestion');
}
Another option is to customizing SwiftMailer Message - https://laravel.com/docs/8.x/mail#customizing-the-swiftmailer-message.
->withSwiftMessage(function ($message) use ($senderEmail) {
$message->getHeaders()
->addTextHeader('Return-Path', $senderEmail);
})