Codeigniter 3 SMTP with Office 365 - php

I am having difficulties sending email via SMTP using CI3 and Office 365.
My website is hosted with BT.
I found this sample code which I am using, it's the minimum test code for successful email sending over SMTP with Office 365.
In my contact controller I have the following code;
class Contact extends CI_Controller {
public function test(){
$config = [
'protocol' => 'mail',
'smtp_host' => 'smtp.office365.com',
'smtp_user' => 'MY_EMAIL',
'smtp_pass' => 'MY_PASSWORD',
'smtp_crypto' => 'tls',
'newline' => "\r\n",
'smtp_port' => 587,
'mailtype' => 'html'
];
$this->load->library('email', $config);
$this->email->from('MY_FROM_EMAIL');
$this->email->to('MY_TO_EMAIL');
$this->email->subject('Test');
$this->email->message('SMTP sending test');
$sent = $this->email->send();
if ($sent) {
echo 'OK';
} else {
echo $this->email->print_debugger();
}
}
}
When I visit my URL example.com/contact/test I see the following error;
A PHP Error was encountered
Severity: Warning
Message: fsockopen(): unable to connect to smtp.office365.com:587
(Connection timed out)
Filename: libraries/Email.php
Line Number: 1990
Backtrace:
File: .../controllers/Contact.php Line: 118 Function: send
File: ../index.php Line: 341 Function: require_once
Then below that;
The following SMTP error was encountered: 110 Connection timed out
Unable to send email using PHP SMTP. Your server might not be
configured to send mail using this method.
User-Agent: CodeIgniter
Date: Tue, 14 Nov 2017 15:08:27 +0000
etc ...
etc ...
etc ...
I know the login details are correct for the email account as I am able to login and send/receive emails using various email clients.
Any ideas why this is happening, and how I can fix it? Are there any other tests I can carry put in order to help troubleshoot the issue.
I've been stuck at this for days. I don't want to use gmail or any other email provider.

Related

Laravel 5.4 SMTP emails not working

I am using laravel 5.4 and configured gmail smtp details for sending emails. Below is code and return expection error.
Email Code:
try {
Mail::raw('Text', function ($message) {
$message->to('lpkapil#mailinator.com');
});
} catch (\Exception $e) {
echo "<pre>";
print_r($e->getMessage());
print_r($e->getCode());
echo "</pre>";
die();
}
Returned Execption Message & Error code
Error Message:
Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
Error Code:
530
Gmail smtp details used:
MAIL_HOST: smtp.gmail.com
MAIL_PORT: 587
MAIL_ENCRYPTION: tls
username: gmail id
password: password
Please suggest a solution.
This is a easy way to send mails using Laravel.You can use this function on your controller. You have to make a blade template file as example "emailfile.blade.php" with what ever the details you want to show on the email and pass the variables to that blade using the inputs array as I mentioned below.
$inputs = array(
'name'=> 'Your Name',
'address' =>'Your Address',
'company' =>'Your Company',
);
Mail::send('emailfile', $inputs, function ($message) {
$message->from('sender#gmail.com', 'Sender Name');
$message->to('reciver#gmail.com',$name=null)->subject('Mail Subject!');
$message->cc('cc#gmail.com');
});

How do i send email through Codeigniter on some event?

I am using Codeigniter. In a User management Module i want to send an email to user if status is activated. My Email code is working but there is problem with my condition check whether his status is changed or not. I mean i want to send email only if his status is changed to Active.
Below Is My Controller Code:
if($_POST['status'] == 'active')
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'Myhost',
'smtp_port' => 25,
'smtp_user' => 'user',
'smtp_pass' => 'pass',
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('test#test.com', 'Rajan');
$this->email->to($_POST['email']);
$this->email->subject('Your Account Has Been SuccessFully Activated.');
$this->email->message('Hi, We have created your Account. Please Login ');
$this->email->send();
if ($this->email->send())
{
echo"Success";
}
else
{
echo '<p class="error_msg">That Email And Password Combination Does Not Exist !</p>';
}
}
When i edit a user and change his status it gets saved in database but the email is not fired. Please help me to solve this bug.
Please try with this if($_POST['status'] == 'Active') since your status post value is "Active" (according to our discussion). The double equal sign (==) is case sensitive when used to compare strings in PHP.

My Mails Is Always Going To Spam Folder Even Delivering Very Late In Codeigniter Php

I'm Trying To Send Mails From My Web Server Using SMTP PROTOCOL in codeigniter frame work.my mails was always delivering late and going to spam.i had follow many past conservations,still i didn't solve this problem.help me folks to solve this problem.here is my code:
$config = Array('protocol' => 'smtp',
'smtp_host' => 'http://smtp.tfas.net/',
'smtp_port' => 465,
'smtp_user' => 'info#tfas.net',
'smtp_pass' => 'xxxxxxx',
'mailtype' => 'html',
'mailpath' => '/usr/sbin/sendmail',
'charset' => 'utf-8'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
if (file_exists($attachment_path))
{
$this->email->attach("$attachment_path");
$this->email->from('info#tfas.net','TFAS MEMBER PORTAL');
$this->email->reply_to('info#tfas.net','Help Center');
$this->email->message($message);
$this->email->to($to);
$this->email->subject('Greetings From TFAS Member Portal');
}
else
{
$this->email->from('info#tfas.net','TFAS MEMBER PORTAL');
$this->email->reply_to('info#tfas.net','Help Center');
$this->email->message($message);
$this->email->to($to);
$this->email->subject('Greetings From TFAS Member Portal');
}
if($this->email->send())
{
return true;
}
else
{
return false;
}
// Even I had gone through this link https://github.com/ivantcholakov/codeigniter-phpmailer which is a tutorial to send mails with phpmailer library in codeigniter but same problem araises..
I don't think this is an issue with codeigniter's mailer. Usually, emails are marked as spam by email service providers based on the content or an IP filter. In your case it's possible that your content appear spam-like due to not having relevant text and images. Google and most providers has a list of spam words that they look out for when evaluating the spam-ness of your emails. Check this out as it may be help you to find a useful lead: http://blog.hubspot.com/blog/tabid/6307/bid/30684/The-Ultimate-List-of-Email-SPAM-Trigger-Words.aspx

Swiftmailer config : send mail using gmail

I can send email from my pc using swiftmailer, but mail not sending in server.
I'm using swiftmailer 5.0.1. Project details are,
A simple php project in netbeans
swiftmailer 5.0.1
twig 1.13.1
My code is
public function init() {
$this->username = 'username#gmail.com';
$this->password = 'password';
$this->host = 'ssl://smtp.gmail.com';
$this->port = 465;
$this->from = 'username#gmail.com';
$this->subject = 'Company - contact';
$this->body_part_type = 'text/html';
}
public function send_email($from_name_add, $to_add, $fullname, $email, $mobile, $content) {
$this->init();
$transport = Swift_SmtpTransport::newInstance($this->host, $this->port)
->setUsername($this->username)
->setPassword($this->password);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$cid = $message->embed(Swift_Image::fromPath('../public_html/pic/logo.png'));
$this->body = $this->renderEmailTemplate('email', $fullname, $email, $mobile, $content, $cid);
$message->setSubject($this->subject)
->setFrom(array('username#gmail.com' => '' . $from_name_add))
->setTo($to_add)
->setContentType($this->body_part_type)
->setBody($this->body);
$result = $mailer->send($message);
return $result;
}
This code works FINE in my pc. But after upload this code/project to server, mail not sending. Error is,
<br />
<b>Fatal error</b>: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host ssl://smtp.gmail.com [Connection timed out #110]' in /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php:259
Stack trace:
#0 /home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php(64): Swift_Transport_StreamBuffer->_establishSocketConnection()
#1 /home/am***/lib/Swift/classes/Swift/Transport/AbstractSmtpTransport.php(115): Swift_Transport_StreamBuffer->initialize(Array)
#2 /home/am***/lib/Swift/classes/Swift/Mailer.php(80): Swift_Transport_AbstractSmtpTransport->start()
#3 /home/am***/controller/send_mail.php(54): Swift_Mailer->send(Object(Swift_Message))
#4 /home/am***/public_html/contact.php(43): send_mail->send_email('Am*** Inc', 'fe****#gma...', 'asdf', 'asdf#in.com', '111111111111', 'Testing mail')
#5 {main}
thrown in <b>/home/am***/lib/Swift/classes/Swift/Transport/StreamBuffer.php</b> on line <b>259</b><br />
HINT: There is an allready running php symfony2 project in that server, this project can send mail successfully.
Here is the symfony2 code,
$message = \Swift_Message::newInstance()
->setSubject($sub)->setFrom($from)->setTo($to)->setContentType("text/html")
->setBody($this->renderView('FZAm***Bundle:Layout:mail.html.twig', array
('name' => $this->fullname, 'mobile' => $this->mobile, 'email' => $this->email,
'content' => $this->content, 'time' => $this->sys_time, 'ip' => $userip,
'server_time' => date('Y-m-d H:i:s'))
));
try {
$this->get('mailer')->send($message);
// catch and other follows.
Config details are,
mail_contact_from: username#gmail.com
mail_contact_to: username#gmail.com
mail_contact_sub: Contact info
I passed only this details and all settings are default. If any info needed please ask i'l post.
Reason i'm changing from symfony2 project to this ordinary php+swift+twig is my hosting is only 100mb and i need to upload more images. But symfony2 occupy more space.
Looks like your live server is missing OpenSSL, so you need to enable it in order to get secure connections working (i.e. enable the php_openssl module). Also check this question.
After some search in google.
To send mail using gmail auth you need to use this code,
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465);
This is the correct way to send mail. This mail will be send by gmail.
PHP use mail() to send just a mail,
mail($to,$subject,$message,$headers);
This code sends a mail using php code.
Swiftmailer can also send a mail using this php mail() function,
Here is swift code.
$transport = Swift_MailTransport::newInstance();
// nothing inside ()
The problem in this mail is, gmail displays following message,
This message may not have been sent by: username#gmail.com
Sometimes this mail will go to spam.

Codeigniter: unable to send email

I have a "Contact Us" page, where if users submit the form. Then email should go to the specified email.
After submiting the form i am getting the Success message ,but i am not seeing any email in my inbox/spam.
I am testing on my live server.
Pelase help me to solve my problem.
My code:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class contact extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->library('email');
$this->load->model('shopmodel');
$this->load->model('contactusmodel');
$this->load->library('form_validation');
}
function index()
{
$this->form_validation->set_error_delimiters(' <li class="errorlist">', '</li>')->set_rules('fullname', 'Name','trim|required|min_length[5]|max_length[50]|xss_clean');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('countryname', 'Country','trim|required|min_length[2]|max_length[50]|xss_clean');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('contactdetails', 'Contact Details','trim|required|min_length[40]|max_length[2000]|xss_clean');
$data=$this->contactusmodel->contactusmodel();
$data["query"] = $this->shopmodel->getshopdetailsById(199);//taking data as shop id 199
if($this->form_validation->run() === FALSE)
{
$data['ffullname']['value'] = $this->input->post('fullname');
$data['fcountryname']['value'] =$this->input->post('email');
$data['femail']['value'] = $this->input->post('countryname');
$data['fcontactdetails']['value'] =$this->input->post('contactdetails');
$this->load->view('contact/contact',$data);
}
else if ($this->form_validation->run() === TRUE)
{
$name=$this->input->post('fullname');
$sendersemail=$this->input->post('email');
$fromcountry=$this->input->post('countryname');
$message=$this->input->post('contactdetails');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'ashutosh10g#gmail.com',
'smtp_pass' => 'xxxxxxxx',
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$email_body ="<div>hello world</div>";
$this->email->from('ashutosh10g#gmail.com', 'ddd');
$list = array('ashutosh10g#gmail.com');
$this->email->to($list);
$this->email->subject('Testing Email');
$this->email->message($email_body);
$this->email->send();
echo $this->email->print_debugger();
}
else{
$this->load->view('contact/contact',$data);
}
}
}
?>
What output i am getting is:
[code]
Your message has been successfully sent using the following protocol: mail
From: "ddd"
Return-Path:
Reply-To: "ashutosh10g#gmail.com"
X-Sender: ashutosh10g#gmail.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <513e1456185d4#gmail.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_513e1456185e3"
=?utf-8?Q?Testing_Email?=
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_513e1456185e3
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
hello world
--B_ALT_513e1456185e3
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<div>hello world</div>
--B_ALT_513e1456185e3--
Maybe you are experimenting a relaying error somtimes the Google Server don't accept relay mail form one MTA to another inbox. Try to test to establish an SMTP dialog to your server an try to send the mail. Here is a simple SMTP dialog example:
http://www.soi.wide.ad.jp/class/20000009/slides/11/6.html
Try to send a mail if the server sends a relay error you should try with another SMTP server. If not maybe is a missconfiguration of your php.
But in my experience gmail always deny the relaying mail for spam and security reasons if the MTA is not a trusted agent.
Another reason may be that you don't have correctly configure DNS Servers and your MTA cannot find the MX Records. Example y your MTA is sendmail it notifies php tha the mail was send succesfully but if you look into sendmail logs you can find that the host is unreachable.

Categories