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);
Related
sorry for the noob question. but this was working before, then now it is not. i don't understand why.
please see the codes below
we have a smtp server.
it was working properly, but after afew testing it was like that already.
I could ping the smtp server, it is still alive.
'
package ph.com.autoemailer.util;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.io.IOUtils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Mailer{
String d_email = "<this is not empty>",
d_password = "<this is not empty>",
d_host = "<this is not empty>",
d_port = "<this is not empty>",
m_to = "<this is not empty>",
//m_to = "<this is not empty>",
m_subject = "Auto-Email Notification: Receipt of Payment Confirmation FAO",
m_text = "Hey, this is the testing email.";
String formatMessage = "";
String dearGreetings;
String sbuGreetings;
String part1Message;
String part2Message;
String part2MessageImg;
String tyMessage;
String sbuMessage;
String noteMessage;
String iNoteMessage;
#SuppressWarnings("resource")
public Mailer(){
System.out.println("Start Mailer ...... ");
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
MimeBodyPart attachPart = new MimeBodyPart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
dearGreetings = "<this is not empty>";
sbuGreetings = "<this is not empty>";
part1Message = "<this is not empty>";
part2Message = "<this is not empty>";
part2MessageImg = "<this is not empty>";;
tyMessage = "Yours truly,<br/><br/><br/>";
sbuMessage = "<this is not empty>";
noteMessage = "<this is not empty>";
iNoteMessage = "<this is not empty>";
formatMessage = dearGreetings+sbuGreetings+part1Message+part2Message+part2MessageImg+tyMessage+sbuMessage+noteMessage+iNoteMessage;
m_text = formatMessage;
msg.setText(m_text);
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(m_to));
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
// creates body part for the attachment
messageBodyPart.setContent(formatMessage, "text/html");
InputStream inputStream = null;
OutputStream outputStream = null;
String attachFile = "<this is not empty>";
// read this file into InputStream
inputStream = new FileInputStream(attachFile);
byte[] bytesInputStream = IOUtils.toByteArray(inputStream);
Date getDateToday = new Date();
SimpleDateFormat formatDateToday = new SimpleDateFormat("yyyyMMdd");
String finishFormatDate = formatDateToday.format(getDateToday);
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File("<this is not empty>"+".pdf"));
String convertedattachFile = "<this is not empty>"+".pdf";
DataSource source = new ByteArrayDataSource(bytesInputStream, "application/pdf");//new FileDataSource(convertedattachFile);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(attachFile).getName());
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}finally{
System.out.println("Email Is Sending...");
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_password, d_password);
}
}
public static void main(String[] args) {
Mailer blah = new Mailer();
}
}
here is the error result
Start Mailer ......
DEBUG: setDebug: JavaMail version 1.5.3
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.elasticemail.com", port 2525, isSSL false
220 smtp.elasticemail.com ESMTP
DEBUG SMTP: connected to host "smtp.elasticemail.com", port: 2525
EHLO 10.24.51.120
250-smtp.elasticemail.com
250-PIPELINING
250-SIZE 20971520
250-8BITMIME
250-AUTH=PLAIN LOGIN CRAM-MD5
250-AUTH PLAIN LOGIN CRAM-MD5
250-STARTTLS
250 OK
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "20971520"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH=PLAIN", arg "LOGIN CRAM-MD5"
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN CRAM-MD5"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "OK", arg ""
STARTTLS
220 Begin TLS negotiation
EHLO 10.24.51.120
250-smtp.elasticemail.com
250-PIPELINING
250-SIZE 20971520
250-8BITMIME
250-AUTH=PLAIN LOGIN CRAM-MD5
250-AUTH PLAIN LOGIN CRAM-MD5
250-STARTTLS
250 OK
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "20971520"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH=PLAIN", arg "LOGIN CRAM-MD5"
DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN CRAM-MD5"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "OK", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed
javax.mail.AuthenticationFailedException: 535 Authentication failed: Error: Not enough credit.
Email Is Sending...
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at ph.com.autoemailer.util.Mailer.<init>(Mailer.java:140)
at ph.com.autoemailer.util.Mailer.main(Mailer.java:173)
This error is a custom error. Probably the elasticemail service is a payd service and you haven't enough credit to send emails.
Check your credit.
I really don't know if this is about SwiftMailer or mailtrap.io but the problem is when I try to establish a SMTP connection to said service (mailtrap.io) I never get any errors, even if I don't use any username or password. Am I not supposed to get any authentication errors when not using any username or password? Or am I doing this the wrong way?
This is the method I use to test if the dynamic connection can be made before I store it in the .env file.
/**
* E-mail configuration
*
* #param Request $request
* #return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
public function postEmailConfiguration(Request $request)
{
# Try connecting to the SMTP
try {
$encryption = $request->input('encryption');
if ($encryption == 'null') {
$encryption = NULL;
}
$transport = new Swift_SmtpTransport($request->input('host'), $request->input('port'), $encryption);
$transport->setUsername($request->input('username'));
$transport->setPassword($request->input('password'));
$mailer = new Swift_Mailer($transport);
$mailer->getTransport()->start();
# Update .env file
$this->setEnvironmentValues([
'MAIL_HOST' => $request->input('host'),
'MAIL_PORT' => $request->input('port'),
'MAIL_USERNAME' => $request->input('username'),
'MAIL_PASSWORD' => $request->input('password'),
'MAIL_ENCRYPTION' => $request->input('encryption')
]);
return redirect()->back()->with('success', 'Connection to SMTP establised and saved!');
}
# Could not connect to SMTP
catch (Swift_TransportException $e) {
return redirect()->back()->with('error', 'Could not connect to SMTP server.<br>Error: ' . $e->getMessage());
}
# Could not connect to SMTP
catch (Exception $e) {
return redirect()->back()->with('error', 'Could not connect to SMTP server.<br>Error: ' . $e->getMessage());
}
}
I tested a connection to Gmail with SwiftMailer 6 on Symfony 4.4 and the code below (it's similar to yours) works as expected for me.
So if you want to check if the connection is established without a message sending use the next code:
public function checkConnection()
{
try {
// Create the Transport
$transport = (new \Swift_SmtpTransport(
'smtp.gmail.com',
'587',
'tls'
))
->setUsername('your.username#gmail.com')
->setPassword('yourSuperPassword');
// Create the Mailer using your created Transport
$mailer = new \Swift_Mailer($transport);
$mailer->getTransport()->start();
return true;
} catch (\Swift_TransportException $e) {
return $e->getMessage();
} catch (\Exception $e) {
return $e->getMessage();
}
}
otherwise, it throws an exception:
Swift_TransportException:
Failed to authenticate on SMTP server with username "your.username#gmail.com" using 3 possible authenticators. Authenticator LOGIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials z7sm3020898ljj.98 - gsmtp".
Authenticator PLAIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials z7sm3020898ljj.98 - gsmtp".
Authenticator XOAUTH2 returned Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials z7sm3020898ljj.98 - gsmtp".
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.
i tried to send email through swiftmailer
response code 200 ok but still no email recived.
controller code
public function EmaiAction(Request $request)
{
$mailer = $this->get('mailer');
$logger = new \Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
$message = \Swift_Message::newInstance()
->setSubject('Hello')
->setFrom('mohd#abc.com')
->setTo('***#gmail.com')
->setBody('This is a test email.');
if ($this->get('mailer')->send($message)) {
echo '[SWIFTMAILER] sent email to ';
} else {
echo '[SWIFTMAILER] not sending email: ' . $mailer->dump();
}
die("email send");
}
output
[SWIFTMAILER] sent email to
config.yml
swiftmailer:
disable_delivery: true
transport: smtp
encryption: ssl
port: 465
auth_mode: login
host: smtp.gmail.com
username: ***#gmail.com
password: passwrd
delivery_address: abc#gmail.com
on doing echo in if/else its going in if condition that means its true.
so why im not recieving emails.
no error logs appears while sending an emails
im using cpanel app is production enviornment.
disable_delivery: true
This disables mail sending for development (See Docs)
Additionally try the swiftmailer config like this
swiftmailer:
transport: gmail
username: ***#gmail.com
password: passwrd
$message = \Swift_Message::newInstance()
->setSubject('Hello')
->setFrom('mohd#abc.com')
->setTo('***#gmail.com')
->setBody('This is a test email.');
$this->get('mailer')->send($message);
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 .