I created a contact form in Symfony2. I would like to send it via email and also i want to save the content in the database via Symfony2, for this i created a form. The saving into the database works fine but I never get an email on the production server.
public function createAction(Request $request) {
$entity = new Contact();
$form = $this -> createCreateForm($entity);
$form -> handleRequest($request);
$message = \Swift_Message::newInstance() -> setSubject('Hello Email') -> setFrom('newsletter#donaci.ch') -> setTo('me#joelschmid.ch') -> setBody($this -> renderView('DbeDonaciBundle:Contact:email.html.twig', array('entity' => $entity)));
$this -> get('mailer') -> send($message);
$em = $this -> getDoctrine() -> getManager();
$em -> persist($entity);
$em -> flush();
$this -> get('session') -> getFlashBag() -> add('messageSent', 'Die Nachricht wurde erfolgreich abgeschickt. Wir werden uns sobald als möglich bei dir melden!');
return $this -> render('DbeDonaciBundle:Aboutus:index.html.twig', array('entity' => $entity, 'form' => $form -> createView(), ));
}
Locally this seems to work, if I access the message block in the developer toolbar I have an email ready:
Mailer default (default mailer)
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=utf-8
MIME-Version: 1.0
Date: Tue, 04 Mar 2014 10:54:07 +0100
Message-ID: <725cbd36eaafdc75ede3eeb016a60b1d#localhost>
From: newsletter#donaci.ch
Subject: Hello Email
To: me#joelschmid.ch
A contact enquiry was made by asdf at 2014-03-04 10:54.
Reply-To: asdf#memememe.com
Subject: asdf
Body:
Name: asdf
E-Mail: asdf#memememe.com
Message: asdf
Website: asdf
Also there is no e-mail in the spool if I execute:
php app/console swiftmailer:spool:send
Here is the adjusted configfile with mailjet:
mailer_transport: smtp
mailer_host: in.mailjet.com
mailer_user: 3d32164c00c29asdflkjabf2d1e45b
mailer_password: 342f84sdaj7a3d374eb85523dfad246
locale: en
secret: 34af84cbbb7a3d12li552cfgad246
Any ideas? Thanks in advance for your help guys!
it should be relative to smtp server : if symfony debug shows you the mail, it's definetly this.
Try using a dedicated smtp service such as mailjet ( www.mailjet.com ) to handle your emails sending .
Related
I just hanged up to send server emails.
I'm preparing email sending code like this:
$email_config = Array(
'charset' => 'utf-8',
'mailType' => 'html'
);
$email = \Config\Services::email();
$email->initialize($email_config);
$email->setNewline("\r\n");
$email->setCRLF("\r\n");
$email->setFrom("test#mysite.com", "Sender name");
$email->setTo("receiver#gmail.com");
$email->setSubject("Test message");
$email->setMessage("Hello");
if ($email->send()) {
echo "Email sent!";
} else {
echo $email->printDebugger();
return false;
}
It's showing this error message:
Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.
Date: Thu, 4 Jun 2020 05:21:47 -0500
From: "Sender name" <test#mysite.com>
Return-Path: <test#mysite.com>
Reply-To: <test#mysite.com>
User-Agent: CodeIgniter
X-Sender: test#mysite.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <5ed8cb3ba9e500.94682473#mysite.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_5ed8cb3ba9e702.65790334"
=?UTF-8?Q?Test=20message?=
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_5ed8cb3ba9e702.65790334
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Hello
--B_ALT_5ed8cb3ba9e702.65790334
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Hello
--B_ALT_5ed8cb3ba9e702.65790334--
And giving an error in error log:
Email: sendWithMail throwed Use of undefined constant INTL_IDNA_VARIANT_UTS46 - assumed 'INTL_IDNA_VARIANT_UTS46' (this will throw an Error in a future version of PHP)
I want to mention that,
intl extension is enabled in server.
I'm using cPanel.
It was working fine on Codeigniter 3.
The mail function is working with the row method in my server like this:
$to = 'receiver#gmail.com';
$subject = 'Test message';
$message = 'Hello';
$headers = 'From: test#mysite.com' . "\r\n" .
'Reply-To: test#mysite.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Please help.
Thanks in advance.
You need to setup an MTA on your server (Mail Transfer Agent).
For instance: Postfix or exim, and in some cases nullmailer will do the trick
Possibly you can connect to an SMTP relay of your provider
codeigniter provide alternative types ( Mail, Sendmail and SMTP ) check your cpanel outgoing email configuration or ask your provider to check for php's mail() configuration
I ran into this today, and was surprised to see the library failed out of the box. Seems to be an issue in CI's email lib here:
/**
* Validate email for shell
*
* Applies stricter, shell-safe validation to email addresses.
* Introduced to prevent RCE via sendmail's -f option.
*
* #see https://github.com/codeigniter4/CodeIgniter/issues/4963
* #see https://gist.github.com/Zenexer/40d02da5e07f151adeaeeaa11af9ab36
* #license https://creativecommons.org/publicdomain/zero/1.0/ CC0 1.0, Public Domain
*
* Credits for the base concept go to Paul Buonopane <paul#namepros.com>
*
* #param string $email
*
* #return boolean
*/
protected function validateEmailForShell(&$email)
{
if (function_exists('idn_to_ascii') && $atpos = strpos($email, '#'))
{
$email = static::substr($email, 0, ++$atpos)
. idn_to_ascii(static::substr($email, $atpos), 0, INTL_IDNA_VARIANT_UTS46);
}
return (filter_var($email, FILTER_VALIDATE_EMAIL) === $email && preg_match('#\A[a-z0-9._+-]+#[a-z0-9.-]{1,253}\z#i', $email));
}
I don't have time to investigate what this method is all about (wasted a few hours on this already!), but was able to bypass it and send emails successfully.
Create App/Libraries/Email.php to override the problematic method:
<?php namespace App\Libraries;
class Email extends \CodeIgniter\Email\Email{
protected function validateEmailForShell(&$email){
return TRUE;
}
}
Then make the service return your subclass in App/Config/Services.php:
public static function email(bool $getShared=TRUE){
return $getShared ? static::getSharedInstance('email') : new \App\Libraries\Email();
}
Got a solution from CI forum.
From phpinfo() > intl > ICU version was 4.6 in my case. Which is too old.
Updating that to the latest version worked for me.
I'm trying to send an email when a user is subscribing in my web site.
To save me time ... I'm using Swift_Mailer with Symfony.
First, I tried to send a mail with the console :
php .\bin\console swiftmailer:email:send
And that's working, the mail was sent and the client received it.
So now I said to myself, I will be able to send emails with the code.
That's my Controller code :
public function register(Request $request, \Swift_Mailer $mailer)
{
// Here saving new user in the database
$this->sendMail($user->getEMail(), $mailer);
$content = $this->renderView("register.html.twig");
return new Response($content);
}
private function sendMail($email, \Swift_Mailer $mailer)
{
$message = (new \Swift_Message('Hello Email'))
->setFrom(['my.email#gmail.com' => "my name"])
->setTo($email)
->setBody('Here is the message itself');
$mailer->send($message);
}
And That's my .env file :
MAILER_URL=gmail://my.email#gmail.com:myPasswordHere#localhost
When I'm trying to send the mail, no error, I tried this StackOverflow link, but no problem, echo "Successfull", but nothing in the Gmail send box and nothing my client email box.
Can you please help me to ... save me time ^^
------------------------------------------------------------- EDIT 1 ------------------------------------------------------------
I never edited the config/packages/swiftmailer.yaml file, that's it's content :
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
------------------------------------------------------------- EDIT 2 ------------------------------------------------------------
I also tryed to make a new transporter with this code :
$transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465))
->setUsername('my.email#gmail.com')
->setPassword('myPasswordHere');
$mailer = new \Swift_Mailer($transport);
And that's the error I get : Connection could not be established with host smtp.gmail.com [php_network_getaddresses: getaddrinfo failed: Unknown host. #0]
------------------------------------------------------------- EDIT 3 ------------------------------------------------------------
I've got a swiftmailer.yaml fil in the config/packages/dev folder and that's it's default content :
# See https://symfony.com/doc/current/email/dev_environment.html
swiftmailer:
# send all emails to a specific address
#delivery_addresses: ['me#example.com']
I tried to put the same content as in the config/packages/swiftmailer.yaml, but no result.
I don't see something like this in your code:
// Create the Transport
$transport = (new \Swift_SmtpTransport('mail hoster etc', port))
->setUsername('your email')
->setPassword('your password');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
Maybe it's a reason why your mails isn't sent.
Recently moved an existing CodeIgniter product to its own VPS, everything is working away. However, for some reason a password has been invalidated and when the forgot_password function is run the email arrives with an intact subject line, however, the emails have no content. At all. This is the offending code:
function _send_email($type, $email, &$data) {
$this->load->library('email');
$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->to($email);
$this->email->subject(sprintf($this->lang->line('auth_subject_' . $type), $this->config->item('website_name', 'tank_auth')));
$this->email->message($this->load->view('email/' . $type . '-html', $data, TRUE));
echo $this->load->view('email/' . $type . '-html', $data, TRUE);
$this->email->set_alt_message($this->load->view('email/' . $type . '-txt', $data, TRUE));
$this->email->send();
}
I wrote a short PHP script to send an email using the same CodeIgniter library:
<?php
if(!defined('BASEPATH'))
exit('No direct script access allowed');
class EmailTest extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('tank_auth');
$this->lang->load('tank_auth');
}
function sendTest(){
$this->load->library('email');
$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
//$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->to('cameron.j.leafe#gmail.com');
$this->email->subject("Here and There");
$this->email->message("I hear you are an example");
$this->email->send();
echo $this->email->print_debugger();
}
}
?>
That email lands completely fine, and produces this output:
User-Agent: CodeIgniter
Date: Mon, 14 Apr 2014 18:55:55 +1000
From: "EPI Dashboard" <epi#epidashboard.com>
Return-Path: <epi#epidashboard.com>
Reply-To: "epi#epidashboard.com" <epi#epidashboard.com>
X-Sender: epi#epidashboard.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <534ba29b87010#epidashboard.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_534ba29b8708b"
=?utf-8?Q?Here_and_There?=
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_534ba29b8708b
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
I hear you are an example
--B_ALT_534ba29b8708b
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
I hear you are an example
--B_ALT_534ba29b8708b--
The server is a CentOS 6 VPS running postfix and obviously PHP/MySql/Apache.
Any thoughts on what to check or any resources that you can think of would be greatly appreciated.
The PHP.INI file for this server need to have the line:
sendmail_path = /usr/sbin/sendmail -t -i
Which fixed the problem instantly. Not entirely sure as to why parts of the email were showing up and not the body, but it works.
First I tried send it using telnet:
$ telnet smtp.yandex.ru 25
Trying 77.88.21.38...
Connected to smtp.yandex.ru.
Escape character is '^]'.
220 smtp12.mail.yandex.net ESMTP (Want to use Yandex.Mail for your domain? Visit http://pdd.yandex.ru)
EHLO yandex.ru
250-smtp12.mail.yandex.net
250-8BITMIME
250-PIPELINING
250-SIZE 42991616
250-STARTTLS
250-AUTH LOGIN PLAIN
250-DSN
250 ENHANCEDSTATUSCODES
AUTH LOGIN
334 VXNlcm5hbWU6
bWFpbEBua3QubWU=
334 UGFzc3dvcmQ6
*******
235 2.7.0 Authentication successful.
MAIL FROM:mail#nkt.me
250 2.1.0 <mail#nkt.me> ok
RCPT TO:dev#nkt.me
250 2.1.5 <dev#nkt.me> recipient ok
DATA
354 Enter mail, end with "." on a line by itself
Subject: Q^BP5Q^AQ^B
To: dev#nkt.me
.
250 2.0.0 Ok: queued on smtp12.mail.yandex.net as 6VPPHaRoyW-LYnSwHm7
QUIT
221 2.0.0 Closing connection.
Connection closed by foreign host.
All is ok, I got the mail
Then I setup swiftmailer params:
mailer_transport: smtp
mailer_host: smtp.yandex.ru
mailer_user: mail#nkt.me
mailer_password: *****
mailer_auth_mode: login
mailer_encryption: ~
mailer_port: 25
And create command for send emails:
class SendMailCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('mail:send')
->setDescription('Send email')
->addOption('to', null, InputOption::VALUE_REQUIRED, 'Destination email address')
->addOption('body', 'b', InputOption::VALUE_REQUIRED, 'Mail body')
->addOption('subject', 'sub', InputOption::VALUE_OPTIONAL, 'Mail title');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$mailer = $this->getContainer()->get('mailer');
$to = $input->getOption('to');
$subject = $input->getOption('subject');
$body = $input->getOption('body');
$message = \Swift_Message::newInstance()
->setTo($to)
->setSubject($subject)
->setBody($body);
$output->writeln('To: ' . $to);
$output->writeln('Subject: ' . $subject);
$output->writeln('Body: ' . $body);
$output->writeln('Result: ' . $mailer->send($message));
}
}
And run it:
$ app/console mail:send --to="dev#nkt.me" --body="Test body" --subject="Test"
To: dev#nkt.me
Subject: Test
Body: Test body
Result: 1
Well, actually not, otherwise I wouldn't have posted the question.
I tried to use ssl, but still not working, what could be the problem?
PS Now i get smtp instead of spool:
protected function execute(InputInterface $input, OutputInterface $output)
{
$mailer = $this->getContainer()->get('swiftmailer.transport.real');
$message = \Swift_Message::newInstance()
->setFrom(['mail#nkt.me' => 'Admin'])
->setTo($input->getOption('to'))
->setSubject($input->getOption('subject'))
->setBody($input->getOption('body'));
$output->writeln(sprintf('Sent %s emails', $mailer->send($message)));
}
But also get error:
[Swift_TransportException]
Expected response code 250 but got code "", with message ""
I got that same error when I sent directly using the transport instead of passing the transport to a swift mailer instance and then sending.
$mailer = new \Swift_Mailer($transport);
$mailer->send($message);
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.