Play Mailer plugin with Play 2.5 - scala

I am struggling with play mailer plugin. I found many references to configure play-mailer plugin to send email using gmail, but none worked.
Here are the details -
Play 2.5
Scala 2.11
mailer plugin - "com.typesafe.play" %% "play-mailer" % "5.0.0"
And here is my code:
application.conf:
play.mailer {
host="smtp.gmail.com"
port=587
ssl=no
tls=yes
user="pariXXXXXX#gmail.com"
password="XXXXXX"
debug=no
timeout=60
connectiontimeout=60
mock=false
}
Controller:
class HomeController #Inject() (
val messagesApi: MessagesApi,
val mailer:MailerClient)
extends Controller with I18nSupport {
def index = Action {
val bodyHtml = Some(views.html.mails.welcome("Pari").toString)
val email = Email(subject = "subject", from = "pari.XXXXX#gmail.com", to = List("pari.XXXXX#gmail.com"), bodyHtml = bodyHtml, bodyText = Some("Hello"), replyTo = None)
mailer.send(email)
Ok("Did you receive my email?")
}
}
Error:
Execution exception[[EmailException: Sending the email to the following server failed : smtp.gmail.com:587]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:280)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:206)
at play.api.GlobalSettings$class.onError(GlobalSettings.scala:160)
at play.api.DefaultGlobal$.onError(GlobalSettings.scala:188)
at play.api.http.GlobalSettingsHttpErrorHandler.onServerError(HttpErrorHandler.scala:98)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:100)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:99)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:344)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:343)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
Caused by: org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:587
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1421)
at org.apache.commons.mail.Email.send(Email.java:1448)
at play.api.libs.mailer.SMTPMailer$$anon$2.send(MailerPlugin.scala:100)
at play.api.libs.mailer.CommonsMailer.send(MailerPlugin.scala:130)
at play.api.libs.mailer.SMTPMailer.send(MailerPlugin.scala:110)
at play.api.libs.mailer.SMTPDynamicMailer.send(MailerPlugin.scala:117)
at controllers.HomeController$$anonfun$index$1.apply(HomeController.scala:82)
at controllers.HomeController$$anonfun$index$1.apply(HomeController.scala:79)
at play.api.mvc.ActionBuilder$$anonfun$apply$14.apply(Action.scala:403)
at play.api.mvc.ActionBuilder$$anonfun$apply$14.apply(Action.scala:403)
Caused by: javax.mail.MessagingException: Exception reading response
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1939)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1411)
at org.apache.commons.mail.Email.send(Email.java:1448)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1939)
Any thoughts?
P.S. I have enabled less secure access for gmail account as well.

You simply need to provide play mailer configuration in your application.conf as below
play.mailer.host= "smtp.gmail.com"
play.mailer.port= "46"
play.mailer.ssl= true
play.mailer.user="pari.XXXX#gmail.com"
play.mailer.password="XXXXXXXXXX"

I have replaced play.mailer block with smtp.mock. After this change I am getting email sent by application.
smtp.mock=false
smtp {
host="smtp.gmail.com" #example:
port="465" #example: 465
ssl=true
user="pari.XXXX#gmail.com"
password="XXXXXXXXXX"
from="XXXXXXX"
}
However, I am getting warning -
smtp is deprecated, use play.mailer instead
Anybody has any idea, how to configure mailer configs.
Thanks
Pari

Related

Sending mails form grails does not work

I have a problem with sending mails from grails. Add an exception to port 587, but nothing helped. Still an error occur:
Connection refused: connect. Stacktrace follows:
java.lang.reflect.InvocationTargetException: null
at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsControllerClass.java:211)
at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrailsControllerClass.java:188)
at org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsInfoHandlerAdapter.groovy:90)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:432)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
at grails.plugins.mail.MailMessageBuilder.sendMessage(MailMessageBuilder.groovy:131)
at grails.plugins.mail.MailService.sendMail(MailService.groovy:55)
at grails.plugins.mail.MailService.sendMail(MailService.groovy:59)
at grailsproject.UserController.save(UserController.groovy:31)
... 14 common frames omitted
Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2118)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:421)
... 20 common frames omitted
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2084)
... 24 common frames omitted
application.yml
mail:
host: "smtp.gmail.com"
port: 465
username: "***#gmail.com"
password: "***"
props:
mail.smtp.auth: "true"
mail.smtp.socketFactory.port: "465"
mail.smtp.socketFactory.class: "javax.net.ssl.SSLSocketFactory"
mail.smtp.socketFactory.fallback: "true"
build.gradle
runtime "org.grails.plugins:mail:2.0.0.RC4"
I have tried also with:
runtime "org.grails.plugins:mail:2.0.0"
runtime "org.grails.plugins:mail:2.0.0.RC6"
and also does not work.
UserController.groovy
package grailsproject
class UserController {
def mailService
def form() {
}
def save() {
def user = new Userr(params)
user.validate()
if(user.hasErrors())
{
user.errors.allErrors.each {
println it
}
render (view:"/registrationForm/registrationForm", model: [user: user]);
}else
{
user.save(flush: true)
render(view: "user", model: [user: user]);
}
mailService.sendMail{
to "***#gmail.com"
from "***#gmail.com"
subject "This is a test mail"
body "Hello, This is a test mail, how are you?"
}
}
}
I do not have idea, what else should I check...
I am also wondering why it try to connect localhost when I gave there gmail host?
Your application.yml should be
grails:
mail:
host: "smtp.gmail.com"
port: 465
username: "your_mail#gmail.com"
password: "Your_password"
props:
mail.smtp.auth: "true"
mail.smtp.socketFactory.port: "465"
mail.smtp.socketFactory.class: "javax.net.ssl.SSLSocketFactory"
mail.smtp.socketFactory.fallback: "false"
build.gradle wiil be
compile "org.grails.plugins:mail:2.0.0.RC6"
UserController.groovy should be
package grailsproject
class UserController {
def index() { }
def send() {
def multipartFile = request.getFile('attachment')
sendMail {
multipart true
to params.address
subject params.subject
html params.body
if(multipartFile && !multipartFile.empty) {
File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + multipartFile.getOriginalFilename());
multipartFile.transferTo(tmpFile);
attach tmpFile
}
}
flash.message = "Email Sent Successfully"
redirect action:"index"
}
}

Could not send Protocol Buffer message from Akka Cluster Client

I am trying to use Play Framework (Scala) as Akka Cluster client to send messages to another Akka Cluster running my app services.
Here is what I did:
I defined messages in different module using Protocol Buffer and shared between project running Services and Play app (using git submodules)
syntax = "proto2";
option java_package = "com.myproject.api.common.messages";
option java_outer_classname = "IsValidClientMessage";
message IsValidClient {
required int32 clientId = 1;
required string clientSecret = 2;
}
Started Services in port 2560
akka {
remote.netty.tcp.port=${?AKKA_REMOTE_PORT}
remote.netty.tcp.hostname=127.0.0.1
cluster {
seed-nodes = [
"akka.tcp://ApiServiceActorSystem#127.0.0.1:2560"
]
auto-down-unreachable-after = 10s
}
extensions = ["akka.cluster.client.ClusterClientReceptionist"]
loglevel = DEBUG
actor {
serializer {
proto = "akka.remote.serialization.ProtobufSerializer"
}
serialization-bindings {
"com.myproject.api.common.messages.IsValidClientMessage$IsValidClient" = proto
}
serialize-messages = on
provider = "akka.cluster.ClusterActorRefProvider"
debug {
receive = on
}
}
}
And ran Play App using below Akka config:
akka {
remote.netty.tcp.port=2552
remote.netty.tcp.hostname=127.0.0.1
remote.enabled-transports = ["akka.remote.netty.tcp"]
cluster {
seed-nodes = [
"akka.tcp://Api#127.0.0.1:2552"
]
auto-down-unreachable-after = 10s
}
extensions = ["akka.cluster.client.ClusterClientReceptionist"]
loglevel = DEBUG
actor {
serializer {
proto = "akka.remote.serialization.ProtobufSerializer"
}
serialization-bindings {
"com.myproject.api.common.messages.IsValidClientMessage$IsValidClient" = proto
}
serialize-messages = on
provider = "akka.cluster.ClusterActorRefProvider"
debug {
receive = on
}
}
}
This is the code I have been trying to send message to ApiServiceSystem:
package com.myproject.api.akka.actors.socket
import ...
class ClientActor extends Actor with ActorLogging {
ClusterClientReceptionist(context.system).registerService(self)
val outActors: ArrayBuffer[ActorRef] = ArrayBuffer.empty
val apiServiceClient = context.system.actorOf(ClusterClient.props(
ClusterClientSettings(context.system).withInitialContacts(Set(ActorPath.fromString("akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist")))
))
override def receive = {
case WatchOutActor(a) =>
context.watch(a)
outActors += a
case Terminated(a) =>
context.unwatch(a)
outActors.remove(outActors.indexOf(a))
case other =>
implicit val to: Timeout = 2 seconds
val isValidClient = IsValidClient.newBuilder() // Protocol Buffer Message
isValidClient.setClientId(1000)
isValidClient.setClientSecret("notsosecret")
(apiServiceClient ? ClusterClient.Send("/user/clientActor", isValidClient.build(), false)).mapTo[Future[Either[ServiceError, Boolean]]] map { f =>
f map {
case Left(e) =>
outActors foreach { a => a ! e.msg }
case Right(bool) =>
outActors foreach { a => a ! bool.toString }
}
} recover {
case e: Exception => println(s"-=> Exception ${e.getMessage}")
}
}
}
object ClientActor {
case class WatchOutActor(actorRef: ActorRef)
}
As I see from below log, that my api has connected to cluster running service:
[DEBUG] [08/11/2016 10:11:05.936] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-24] [akka.remote.Remoting] Associated [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560] <- [akka.tcp://Api#127.0.0.1:2552]
[DEBUG] [08/11/2016 10:11:05.998] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-24] [akka.serialization.Serialization(akka://ApiServiceActorSystem)] Using serializer[akka.cluster.client.protobuf.ClusterClientMessageSerializer] for message [akka.cluster.client.ClusterReceptionist$Internal$GetContacts$]
[DEBUG] [08/11/2016 10:11:06.000] [ApiServiceActorSystem-akka.actor.default-dispatcher-4] [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] Client [akka.tcp://Api#127.0.0.1:2552/user/$a] gets contactPoints [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] (all nodes)
[DEBUG] [08/11/2016 10:11:06.002] [ApiServiceActorSystem-akka.actor.default-dispatcher-4] [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] Client [akka.tcp://Api#127.0.0.1:2552/user/$a] gets contactPoints [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] (all nodes)
[DEBUG] [08/11/2016 10:11:06.002] [ApiServiceActorSystem-akka.actor.default-dispatcher-4] [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] Client [akka.tcp://Api#127.0.0.1:2552/user/$a] gets contactPoints [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] (all nodes)
[DEBUG] [08/11/2016 10:11:06.002] [ApiServiceActorSystem-akka.actor.default-dispatcher-4] [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] Client [akka.tcp://Api#127.0.0.1:2552/user/$a] gets contactPoints [akka.tcp://ApiServiceActorSystem#127.0.0.1:2560/system/receptionist] (all nodes)
[DEBUG] [08/11/2016 10:11:06.004] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-76] [akka.serialization.Serialization(akka://ApiServiceActorSystem)] Using serializer[akka.cluster.client.protobuf.ClusterClientMessageSerializer] for message [akka.cluster.client.ClusterReceptionist$Internal$Contacts]
[DEBUG] [08/11/2016 10:11:06.033] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-76] [akka.serialization.Serialization(akka://ApiServiceActorSystem)] Using serializer[akka.serialization.JavaSerializer] for message [akka.actor.Identify]
[DEBUG] [08/11/2016 10:11:06.037] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-24] [akka.serialization.Serialization(akka://ApiServiceActorSystem)] Using serializer[akka.serialization.JavaSerializer] for message [akka.actor.ActorIdentity]
[DEBUG] [08/11/2016 10:11:06.126] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-76] [akka.serialization.Serialization(akka://ApiServiceActorSystem)] Using serializer[akka.serialization.JavaSerializer] for message [akka.remote.EndpointWriter$AckIdleCheckTimer$]
[DEBUG] [08/11/2016 10:11:07.749] [ApiServiceActorSystem-akka.remote.default-remote-dispatcher-76] [akka.serialization.Serialization(akka://ApiServiceActorSystem)] Using serializer[akka.cluster.client.protobuf.ClusterClientMessageSerializer] for message [akka.cluster.client.ClusterReceptionist$Internal$Heartbeat$]
But whenever I try to send message, I get this error:
java.lang.RuntimeException: Unable to find proto buffer class: com.myproject.api.common.messages.IsValidClientMessage$IsValidClient
at com.google.protobuf.GeneratedMessageLite$SerializedForm.readResolve(GeneratedMessageLite.java:1192)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at java.io.ObjectStreamClass.invokeReadResolve(ObjectStreamClass.java:1104)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1810)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at akka.serialization.JavaSerializer$$anonfun$1.apply(Serializer.scala:241)
at scala.util.DynamicVariable.withValue(DynamicVariable.scala:58)
at akka.serialization.JavaSerializer.fromBinary(Serializer.scala:241)
at akka.serialization.Serialization$$anonfun$deserialize$3.apply(Serialization.scala:142)
at scala.util.Try$.apply(Try.scala:192)
at akka.serialization.Serialization.deserialize(Serialization.scala:142)
at akka.actor.dungeon.Dispatch$class.sendMessage(Dispatch.scala:128)
at akka.actor.ActorCell.sendMessage(ActorCell.scala:374)
at akka.actor.Cell$class.sendMessage(ActorCell.scala:295)
at akka.actor.ActorCell.sendMessage(ActorCell.scala:374)
at akka.actor.RepointableActorRef.$bang(RepointableActorRef.scala:169)
at akka.actor.ActorRef.tell(ActorRef.scala:128)
at akka.pattern.AskableActorRef$.internalAsk$extension(AskSupport.scala:295)
at akka.pattern.AskableActorRef$.$qmark$extension1(AskSupport.scala:281)
at com.myproject.api.akka.actors.socket.ClientActor$$anonfun$receive$1.applyOrElse(ClientActor.scala:43)
at akka.actor.Actor$class.aroundReceive(Actor.scala:480)
at com.myproject.api.akka.actors.socket.ClientActor.aroundReceive(ClientActor.scala:16)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
at akka.actor.ActorCell.invoke(ActorCell.scala:495)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
at akka.dispatch.Mailbox.run(Mailbox.scala:224)
at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.ClassNotFoundException: com.myproject.api.common.messages.IsValidClientMessage$IsValidClient
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.google.protobuf.GeneratedMessageLite$SerializedForm.readResolve(GeneratedMessageLite.java:1183)
... 38 common frames omitted
How can I serialize my message? Why is that ClassNotFoundException occurring at run time? Any help will be much appreciated
It seems there is a class loading issue with akka-remote and protobuf 3.x generated classes (even if you use proto2 definitions). Could solve it using the protobuf 2.5 compiler istead of 3.x: https://github.com/google/protobuf/releases/tag/v2.5.0
You have to compile it yourselve, because there are no precompiled binaries. Just head to the downloaded directory and run the following commands:
./configure
make
make install
After compiling the v2.5 protoc binary, use it to rebuild your java classes and use them. Will open an issue to get proto 3 support in akka.
Clarification: It's not the protobuf-java version, but the classes generated by the protoc binary 3.0
You need to explicitly bind Lite and V3 classes to your proto serializer:
akka {
loglevel = "INFO"
actor {
provider = "akka.remote.RemoteActorRefProvider"
serializers {
proto = "akka.remote.serialization.ProtobufSerializer" # or use your own..
}
serialization-bindings {
"com.google.protobuf.Message" = proto
"com.google.protobuf.GeneratedMessageLite" = proto
"com.google.protobuf.GeneratedMessageV3" = proto
}
}

Having trouble mocking an email server using JUnit

I'm trying to mock sending an email (for the purposes of JUnit, v4.8.1, testing) and decided to use Dumbster, which I found through SO. I'm using version 1.6. I have this in my JUnit test …
SimpleSmtpServer server = SimpleSmtpServer.start();
boolean ret = m_emailSvc.sendEmail("me#me.com",
"you#you.com",
"localhost",
"Test",
"Test Body");
Assert.assertTrue(ret);
server.stop();
and I send an email this way …
public boolean sendEmail(final String toEmail,
final String fromEmail,
final String smtpHost,
final String subject,
final String body)
{
boolean ret = true;
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", smtpHost);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmail));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(body);
// Send message
Transport.send(message);
}catch (MessagingException mex) {
ret = false;
LOG.error(mex.getMessage(), mex);
} // try
return ret;
} // sendEmail
This fails with the exception below. Does anyone know what I'm doing wrong or is there an easier way to mock sending an email in a JUnit test?
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:521)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:414)
at java.net.ServerSocket.bind(ServerSocket.java:326)
at java.net.ServerSocket.<init>(ServerSocket.java:192)
at java.net.ServerSocket.<init>(ServerSocket.java:104)
at com.dumbster.smtp.SimpleSmtpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:680)
[ERROR]: org.mainco.subco.email.service.EmailServiceImpl - Could not connect to SMTP host: localhost, port: 25
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.mainco.subco.email.service.EmailServiceImpl.sendEmail(EmailServiceImpl.java:62)
at org.mainco.subco.email.service.EmailServiceTest.testSendEmail(EmailServiceTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:527)
at java.net.Socket.connect(Socket.java:476)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
I decided to mock the static call from the Transport class instead, using PowerMock (v.1.5.1).
#RunWith(PowerMockRunner.class)
public class EmailServiceTest
{
#Autowired
private EmailService m_emailSvc = new EmailServiceImpl();
#Test
#PrepareForTest( Transport.class )
public final void testSendEmail()
{
suppress(methodsDeclaredIn(Transport.class));
boolean ret = m_emailSvc.sendEmail("me#me.com",
"you#you.com",
"localhost",
"Test",
"Test Body");
Assert.assertTrue(ret);
} // testSendEmail
What about wrapping the call to Transport is a mockable object? Inject the mock and verify the call.
What I mean is something like this...
class MyTransport{
public void send(MimeMessage message){
Transport.send(message);
}
}
Then inject an instance of this class into your class above. In your production env you have the same code. However, when doing testing you could pass in a Mock for MyTransport and thereby verify the call to send without the need of a server.

gerrit -application error server error connection refused

In gerrit,While registering with a open id(gmail) for the first time it got registered no issues ,but when I add another user with a open id(gmail) [settings->Contact Information->Register New Email] am getting an error like this,
Application error
Server error
Connection refused
What kind of problem is it.My config file
[sendemail]
enable = true
smtpUser = *xxxxx*#gmail.com
smtpPass = "xxxx"
smtpServerPort = 25
smtpServer = 127.0.0.1
smtpEncryption = none
sslVerify = true
from = MIXED***
My error log goes like this
com.google.gerrit.httpd.rpc.account.AccountSecurityImpl : Cannot send email verification message to %$%$###gmail.com
com.google.gerrit.server.mail.EmailException: Connection refused
at com.google.gerrit.server.mail.SmtpEmailSender.open(SmtpEmailSender.java:245)
at com.google.gerrit.server.mail.SmtpEmailSender.send(SmtpEmailSender.java:152)
at com.google.gerrit.server.mail.OutgoingEmail.send(OutgoingEmail.java:116)
at com.google.gerrit.httpd.rpc.account.AccountSecurityImpl.registerEmail(AccountSecurityImpl.java:311)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwtjsonrpc.server.MethodHandle.invoke(MethodHandle.java:91)
at com.google.gwtjsonrpc.server.JsonServlet.doService(JsonServlet.java:382)
at com.google.gwtjsonrpc.server.JsonServlet.service(JsonServlet.java:268)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:216)
at com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:141)
at com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:93)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:63)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:134)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:59)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:134)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:59)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:134)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:59)
at com.google.gwtexpui.server.CacheControlFilter.doFilter(CacheControlFilter.java:76)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:129)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:59)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:134)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:59)
at com.google.gerrit.httpd.RequestCleanupFilter.doFilter(RequestCleanupFilter.java:54)
at com.google.inject.servlet.FilterDefinition.doFilter(FilterDefinition.java:129)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:59)
at com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:122)
at com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:110)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1322)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:473)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:921)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:403)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:856)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:114)
at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:114)
at org.eclipse.jetty.server.Server.handle(Server.java:352)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:596)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.content(HttpConnection.java:1069)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:805)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:218)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:426)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:510)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.access$000(SelectChannelEndPoint.java:34)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:450)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:327)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:193)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:163)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:184)
at com.google.gerrit.server.mail.SmtpEmailSender.open(SmtpEmailSender.java:215)*/
... 51 more
Are you really using your localhost as smtpServer ? It looks like your localhost does not support what you're doing. If you have a GMail account, just use Google smtp.
We use the following config and it works just fine:
[sendemail]
smtpServer = smtp.gmail.com
smtpUser = XXX#gmail.com
smtpEncryption = ssl
smtpPass = XXXXX

Cannot send email in ICEmobile project

I just started to delve into ICEsoft. I have an ICEmobile project in which I try to implement notification sending to users. I use Tomcat 7, ICEmobile 1.1, ICEfaces 3, and my IDE is Eclipse Juno 4.2.
Here are some code snippets for rendering messages:
/** from NotificationBean class (ApplicationScoped) **/
// render group is the current session id.
public String renderGroup = "renderGroup";
public NotificationBean() {
PushRenderer.addCurrentSession(renderGroup);
}
/** from NotificationController class (ViewScoped) **/
NotificationBean notifBean = (NotificationBean)FacesUtils.getManagedBean("notificationBean");
public void sendPriorityPushMessage(ActionEvent event) {
final PushMessage myMessage = new PushMessage(notifBean.getSubject(), notifBean.getMessage());
final PortableRenderer portable = PushRenderer.getPortableRenderer();
...
portable.render(notifBean.renderGroup, myMessage);
...
}
I've configured SMTP setting in my web.xml in such a way:
smtp.host: smtp.gmail.com
smtp.from: myaccount#gmail.com
smtp.port: 465
smtp.user: myaccount#gmail.com
smtp.password ...
smtp.security: SSL
smtp.verify-server-certificate - false
I am testing all this on an Android emulator, in ICEmobile Container (4.1, 16 + Google APIs). There I unchecked C2DM Notify property and in "Email Notification" entered my email address.
With that code I cannot send email. I get such an error:
WARNING: Failed to send email message.
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
at org.icepush.EmailNotificationProvider$SendMessage.run(EmailNotificationProvider.java:138)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:507)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
Do I miss something? I tried to configure my Tomcat, but don't know how to do it properly - maybe the cue is in that?
Thanks in advance,
Irina
I resolved that problem by updating my mail.jar. Mine was too old.