Email sending in Spring batch - email

I am very new to Spring batch. I have a requirement to send mail from my application after processing some records. Went through many links. But i did not find anything useful. Can somebody help me?

Hi You can try below code, I am using this javax code in my project and working cool..
public void sendMailtoMgr(final String subject, final String message,
String mgrmailIds) {
String mngrecipients = null;
Message msg = null;
InternetAddress[] mgraddress = null;
boolean debug = false;
try {
// Load your SMTP Properties from Property file
Properties props = new Properties();
props.put(SMTP_HOST, SMTP_HOST_VALUE);
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
msg = new MimeMessage(session);
// From value is nothing but from Address , can give your email id
msg.setFrom(new InternetAddress(SMTP_FROM_VALUE));
mngrecipients = mgrmailIds;
mgraddress = addRecipients(mngrecipients);
if (mgraddress != null && mgraddress.length != 0) {
msg.setRecipients(Message.RecipientType.TO, mgraddress);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
}
}
catch (MessagingException mex) {
logger.info("Exception in sendMail()");
mex.printStackTrace();
}
catch (Exception e) {
logger.info("Exception in sendMail()", e);
} finally {
logger.info("Exiting sendMail()");
}
}

You need to implement a JobExecutionListener and add it to your job in the following manner:
<batch:job id="provisionAddOns" >
<batch:step id="cpsProvisionAddOns">
...
</batch:step>
<batch:listeners>
<batch:listener>
<bean class="EmailNotification" />
</batch:listener>
</batch:listeners>
</batch:job>
Here EmailNotification implements JobExecutionListener and send the email in the afterJob() method; you can use any method you like to send emails depending on your needs.

Related

My code receives the message from the queue multiple time, I want to receive it only one time. How can I do it?

I am new, so my question is relatively easy, I guess.
I am using Websphere Application Server platform and default JMS provider to send and receive message from queue. This is how my app looks like:
Saytime is my main servlet which reroute my code to a .jsp file. The "Produce" button sends the app following code and generate the message written in box:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String queueName = "jms/helloqueue";
Context jndiContext = null;
QueueConnectionFactory queueConnectionFcatory = null;
QueueConnection queueConnection = null;
QueueSession queueSession = null;
QueueSender queueSender = null;
Queue queue = null;
TextMessage textMessage = null;
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8"); // To information the that you may use Unicode characters
response.setCharacterEncoding("UTF-8");
String txt = request.getParameter("text");
try {
Properties initialProperties = new Properties();
initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
initialProperties.put(InitialContext.PROVIDER_URL, "iiop://localhost:2810");
jndiContext = new InitialContext(initialProperties);
} catch (NamingException e) {
e.printStackTrace();
System.exit(1);
}
try {
queueConnectionFcatory = (QueueConnectionFactory) jndiContext.lookup("jms/helloqcf");
queue = (Queue) jndiContext.lookup(queueName);
} catch (NamingException e) {
e.printStackTrace();
System.exit(1);
}
try {
queueConnection = queueConnectionFcatory.createQueueConnection();
queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
queueSender = queueSession.createSender(queue);
textMessage = queueSession.createTextMessage();
textMessage.setText(txt);
queueSender.send(textMessage);
} catch (JMSException e) {
System.out.println("JMS Exception occured: "+ e.getMessage());
} finally {
if(queueConnection != null){
try{
Thread.sleep(6000);
queueConnection.close();
} catch(Exception e){}
}
}
RequestDispatcher rd = request.getRequestDispatcher("saytime");
rd.forward(request,response);
}
The "Receive" button sends my app to following servlet code and receives the message from queue:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String queueName = "jms/helloqueue";
Context jndiContext = null;
QueueConnectionFactory queueConnectionfactory = null;
QueueConnection queueConnection = null;
QueueSession queueSession = null;
QueueReceiver queueReceiver = null;
Queue queue = null;
String text = null;
try {
Properties initialProperties = new Properties();
initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
initialProperties.put(InitialContext.PROVIDER_URL,"iiop://localhost:2810");
jndiContext = new InitialContext(initialProperties);
} catch (NamingException e) {
System.out.println("JNDI exception occured: " + e.getMessage());
System.exit(1);
}
try {
queueConnectionfactory = (QueueConnectionFactory) jndiContext.lookup("jms/helloqcf");
queue = (Queue) jndiContext.lookup(queueName);
} catch (NamingException e) {
System.exit(1);
}
try {
queueConnection = queueConnectionfactory.createQueueConnection();
queueSession = queueConnection.createQueueSession(true,Session.AUTO_ACKNOWLEDGE);
queueReceiver = queueSession.createReceiver(queue);
//queueReceiver.setMessageListener(listener);
queueConnection.start();
text = queueReceiver.receive().toString();
} catch(JMSException e) {
System.out.println("Exception occured: "+ e.getMessage());
} finally {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
}
}
}
if(text != null) {
request.setAttribute("message", text.toString());
}
RequestDispatcher rd = request.getRequestDispatcher("saytime");
rd.forward(request,response);
}
After that I print the message with this little code in my .jsp file:
<%
String getValues = (String) request.getAttribute("message");
%>
<%
if (getValues != null) {
out.println("<p>" + getValues + "</p>");
} else {
out.println("<p> There is no message </p>");
}
%>
The problem is this: I am able to take my produced message, but the button continues to receive the message till the count on JMSXDeliveryCount hit 5. Mostly JMSXDeliveryCount start with 1 and total I can receive the message 5 times. I want to receive it only once and then message to disappear.
Additionally, I want to know how I can print only my message. I print with additional details like you see in the picture. If it's possible, I don't want that.
I tried to limit redelivery number, but I am unable to come up with right code I guess. Also, I tried to use different acknowledgement mode but, it did not work either.
I got really confused with it, some help would be perfect. Thanks.
The problem is you're creating the consumer's session as transacted. See this line:
queueSession = queueConnection.createQueueSession(true,Session.AUTO_ACKNOWLEDGE);
The acknowledgement mode will be ignored since the session is transacted (i.e. you're passing true in the first parameter). This is noted in the documentation which states:
If transacted is set to true then the session will use a local transaction which may subsequently be committed or rolled back by calling the session's commit or rollback methods. The argument acknowledgeMode is ignored.
Therefore, you should either acknowledge the message and commit the session manually, e.g.:
Message message = queueReceiver.receive();
text = message.toString();
message.acknowledge();
queueSession.commit();
Or you should use a non-transacted session and allow the message to be auto-acknowledged according to the acknowledgement mode, e.g.:
queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Typically transacted sessions are only used when multiple operations (i.e. send and receive) need to be combined together atomically. Since you're only consuming a single message here I would recommend you just use a non-transacted session.
Also, you will eventually want to cache the javax.jms.Connection or perhaps use a connection pool rather than creating a connection, session, & producer/consumer for every message. This is an anti-pattern and should be avoided whenever possible.

Netbeans 8.2 - Send email not working after Clean and Build

this is making me crazy :) The code works great when i am coding on netbeans (i mean, it sends all emails i want with success) , but, after Clean and Build, it just dont send any email.
zzzzzzzzzzzzzzzzzz = my password
this is my sendig code:
private void envia_email (String email_selecionado) {
String to = email_selecionado;
String from = "xxxxxxxxxx#gmail.com";
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp" );
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory
try {
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "zzzzzzzzzzz");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("EUROMILIONS PLAY SOFTWARE");
message.setText(corpo_email.getText());
message.setSentDate(new Date());
Transport.send(message);
//JOptionPane.showMessageDialog(null,"Mensagem enviada com sucesso !");
} catch (MessagingException ex) {
teste.setVisible(false);
JOptionPane.showMessageDialog(this,"Erro: "+ex.toString());
//Logger.getLogger(serial_control.class.getName()).log(Level.SEVERE, null, ex);
}
}
what can be wrong ? why it works on netbeans but not works after Clean and Build.
Thanks

Asynchronous email notification in groovy

I have the below code in a groovy class, I want to call this method asynchronously from various other groovy classes.
public void sendNotification(){
//async true
String from = ApplicationConfig.email_From;
String sendTo = ApplicationConfig.email_To;
String host = ApplicationConfig.email_Host;
String subject = ApplicationConfig.email_Subject;
String textToSend = ApplicationConfig.email_Text;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
message.setSubject(subject);
message.setText(textToSend);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
So far I couldn't find anything that fits my requirement, there are some plugins in grails, but I'm not using grails.
Just use an ExecutorService
ExecutorService pool = Executors.newFixedThreadPool(2)
def sender = { ->
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", ApplicationConfig.email_Host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(ApplicationConfig.email_From));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(ApplicationConfig.email_To));
message.setSubject(ApplicationConfig.email_Subject);
message.setText(ApplicationConfig.email_Text);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public void sendNotification() {
pool.submit(sender)
}

How to register new user without need to login?

I have problem with registering new user on my OpenFire server. This is a reply from server.
<iq id='XILKN-9' to='pc-pc/b529612d' from='192.168.21.107' type='error'>
<query xmlns='jabber:iq:register'>
<password>123</password>
<email>bear#bear.com</email>
<username>bear</username>
</query>
<error type="modify">
<bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
</error>
</iq>
But when I login with any existing user before registering new user, I can register new user successfully and this is the reply from server
<iq id='XILKN-15' to='kkk#pc-pc/Smack' from='pc-pc' type='result'></iq>
Here is my code :
String user ="bear";
String pass = "123";
String email = "bear#bear.com";
HashMap<String,String> attr = new HashMap<String, String>();
attr.put("username",user);
attr.put("password",pass);
attr.put("email", email);
if(conn2!=null) {
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(conn2.getServiceName());
reg.setAttributes(attr);
PacketFilter filter = new AndFilter(new PacketIDFilter(
reg.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = conn2 .createPacketCollector(filter);
try {
conn2.sendPacket(reg);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
IQ result = (IQ) collector.nextResult(SmackConfiguration
.getDefaultPacketReplyTimeout());
System.out.println(result);
collector.cancel();
I used OpenFire 3.9.3 and aSmack 4.0.7 .
If I understand you correct I solve this issue by the next steps.
creat connection with the server.
then you use with AccountManager
then you create new account by createAccount
So with should be something like that:
AccountManager am = connection.getAccountManager();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("username", username);
attributes.put("password", password);
attributes.put("email", email);
attributes.put("name", name);
try {
am.createAccount(username, password,attributes);
Toast.makeText(getActivity(),"User create: " + username,Toast.LENGTH_SHORT).show();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Sending mail in blackberry

i want to create an application which can send a email in blackberry. can i have a sample code or tutorial
thanks alot
U can send Email two types using API Directly or Programatically
public void sendemail(String s){
Message m = new Message();
Address a = null;
try
{
a = new Address("","");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address[] addresses = {a};
try
{
m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
m.setContent(s);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.setSubject(" My Croxley ");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));
}
And Another this way
public boolean SendEmail(String emailFrom, String emailTo, String subject, String messageData, String fileName, byte[] fileData)
{
// create a multipart message
Multipart mp = new Multipart();
TextBodyPart tbp = new TextBodyPart(mp, messageData);
mp.addBodyPart(tbp);
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, "audio/amr", fileName, fileData);
mp.addBodyPart(sap);
// create a message in the sent items folder
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
// add recipients to the message and send
try
{
Address toAdd = new Address(emailTo, emailTo);
Address toAdds[] = new Address[1];
toAdds[0] = toAdd;
message.addRecipients(Message.RecipientType.TO, toAdds);
message.setSubject(subject);
message.setContent(mp);
//sets priority
//message.setPriority(Message.Priority.HIGH);
net.rim.blackberry.api.mail.Transport.send(message);
return true;
}
catch (Exception e)
{
return false;
}
}
Ypu can get started with this: http://www.blackberry.com/developers/docs/6.0.0api/Messaging-summary.html#MG_1