My java application is unable to send emails but when I restart the server it will again send emails for 3 to 4 days and again the same issue repeats and throws connection refused and couldn't connect to smtp localhost 465
package com.fps.mail;
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties;
import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart;
import com.fps.exceptions.SystemException; import com.fps.utils.Constants; import com.fps.utils.HelperFunctions; import com.fps.utils.LogHelper;
/* * A singleton thread that handles all the mailings within the project. * All mails are sent asynchronously, at specific intervals *
* Contains wrapper methods to send mail using the Java Mail API. /
/ * Modification Log: (mm/dd/yyyy [Author] Changes) * * 03/16/2004 [Rahul Gedupudi] Base Version * 04/05/2007 [Sunitha Venkataraman] Updated to JDK 1.5 - Parameterized List /
public class MailHandler implements Runnable {
//singleton variable
private static MailHandler instance = new MailHandler();
//contains a list of MailDetail objects representing all the mails that have to be sent
private List<Object> mails = null;
//interval after which the thread checks to send mails
//currently at 10 mins
private static final long INTERVAL = 60000;
//contains the properties to be used for obtaining mail session
private Properties mailProps = null;
/**
-
Private Constructor. Use getInstance().
*/
private MailHandler() {
super();
this.mails = new ArrayList<Object>(1);
//setup mail server properties
this.mailProps = System.getProperties();
this.mailProps.put(Constants.MAIL_PROP, Constants.MAIL_HOST);
this.mailProps.put("mail.smtp.socketFactory.port", "465");
this.mailProps.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
this.mailProps.put("mail.smtp.auth", "true");
this.mailProps.put("mail.smtp.port", "465");
//this.mailProps.put("mail.smtp.starttls.enable","true");
/this.mailProps.put("mail.smtp.port", "25");
this.mailProps.put("mail.smtp.EnableSsl", "false");/
/this.mailProps.put("mail.smtp.socketFactory.port", "25");
this.mailProps.put("mail.smtp.socketFactory.fallback", "false");/
//this.mailProps.put("mail.debug", "true");
//start a thread
Thread mailThread = new Thread(this);
mailThread.start();
} //end constructor
/**
- Gets the instance
- @return Returns a MailHelper
*/
public static MailHandler getInstance() {
return instance;
} //end getInstance
/**
- add a mail detail object to the mails list
*/
public void addMail(MailDetail _mailDetail) {
synchronized (this.mails) {
this.mails.add(_mailDetail);
}
} //end addMail
/**
-
used by the thread to send e-mails at set intervals
*/
public void run() {
while (true) {
//create a new list out of the mails list, and empty out mails list
//this is needed to prevent concurrent access modification exceptions.
List<Object> tempList = null;
synchronized (this.mails) {
tempList = new ArrayList<Object>(this.mails);
this.mails.clear();
}
//move to the top of the iterator
Iterator<Object> iter = tempList.iterator();
//check the e-mail list, and send mails if present
while (iter.hasNext()) {
boolean mailError = false;
MailDetail mailDetail = (MailDetail) iter.next();
try {
this.sendMail(mailDetail);
}
catch (SystemException se) {
LogHelper.getInstance().errorMessage(this, null, "Error sending e-mail", se);
mailError = true;
}
//if there is no mail error, delete this MailDetail object, so it is not sent again
if (!mailError) {
iter.remove();
}
} //end while
//if there are any elements in tempList, add it back to mails list to be taken care of in the next iteration
if (!tempList.isEmpty()) {
for (int i = 0, size = tempList.size(); i < size; i++)
this.addMail((MailDetail) tempList.get(i));
}
try {
Thread.sleep(INTERVAL); //sleep for interval time
}
catch (InterruptedException ie) {
//ignore
}
} //end while
} //end run
/**
-
Helper method that returns an object of type InternetAddress from the passed email address string.
-
<br>
-
The boolean variable _from specifies whether this address is for the "From" part of the mail.
-
If set to true, and the passed address is invalid, defaults the address to Constants.MAIL_DEF_ADDR
*/
private Address getEmailAddress(final String _emailAddr, boolean _from) {
Address address = null;
try {
address = new InternetAddress(_emailAddr);
}
catch (AddressException ae) {
LogHelper.getInstance().errorMessage(this, null, "Error trying to obtain mailing address: " + _emailAddr);
//if this method is called for a "from" address, send the default address
if (_from) {
try {
address = new InternetAddress(Constants.MAIL_DEFAULT_ADDR);
}
catch (AddressException aex) {
//ignore -- should not happen
}
}
}
return address;
} //end getEmailAddress
/**
-
Helper method that sends a mail message.
*/
private void sendMail(MailDetail _mailDetail) throws SystemException {
if ((_mailDetail.getToAddresses() == null) || _mailDetail.getToAddresses().isEmpty())
throw new SystemException("Trying to send mail to an empty address list");
//if there is no from address, use the default address
if (HelperFunctions.isEmpty(_mailDetail.getFromAddress(), true)) {
LogHelper.getInstance().warningMessage(this, null, "Trying to send mail with an empty 'to' address");
_mailDetail.setFromAddress(Constants.MAIL_DEFAULT_ADDR);
}
//get the session
Session session = Session.getInstance(this.mailProps, new SMTPAuthenticator());
//define message
MimeMessage message = new MimeMessage(session);
//set the 'from' address
Address fromAddr = this.getEmailAddress(_mailDetail.getFromAddress(), true);
//fromAddr should never be null, as it will contain at least the default address
try {
message.setFrom(fromAddr);
}
catch (MessagingException me) {
throw new SystemException("Invalid 'from' Address: " + _mailDetail.getFromAddress(), me, false);
}
//set the 'to' addresses
for (int i = 0, size = _mailDetail.getToAddresses().size(); i < size; i++) {
Address toAddr = this.getEmailAddress((String) _mailDetail.getToAddresses().get(i), false);
if (toAddr != null)
try {
message.addRecipient(Message.RecipientType.TO, toAddr);
}
catch (MessagingException me) {
throw new SystemException("Invalid 'to' address: " + _mailDetail.getToAddresses().get(i), me, false);
}
} //end for
//set the 'cc' addresses, if present
if (_mailDetail.getCcAddresses() != null)
for (int i = 0, size = _mailDetail.getCcAddresses().size(); i < size; i++) {
Address ccAddr = this.getEmailAddress((String) _mailDetail.getCcAddresses().get(i), false);
if (ccAddr != null)
try {
message.addRecipient(Message.RecipientType.CC, ccAddr);
}
catch (MessagingException me) {
throw new SystemException("Invalid 'cc' address: " + _mailDetail.getCcAddresses().get(i), me, false);
}
} //end for
//set the 'bcc' addresses
if (_mailDetail.getBccAddresses() != null)
for (int i = 0, size = _mailDetail.getBccAddresses().size(); i < size; i++) {
Address bccAddr = this.getEmailAddress((String) _mailDetail.getBccAddresses().get(i), false);
if (bccAddr != null)
try {
message.addRecipient(Message.RecipientType.BCC, bccAddr);
}
catch (MessagingException me) {
throw new SystemException("Invalid 'bcc' address: " + _mailDetail.getBccAddresses().get(i), me, false);
}
} //end for
//set the subject
try {
if (_mailDetail.getSubject() != null)
message.setSubject(_mailDetail.getSubject());
}
catch (MessagingException me) {
throw new SystemException("Error setting subject: " + _mailDetail.getSubject(), me, false);
}
//set the text and attachments
try {
Multipart mp = new MimeMultipart();
//add text
MimeBodyPart textPart = new MimeBodyPart();
if (_mailDetail.getText() != null)
textPart.setContent(_mailDetail.getText(), _mailDetail.getMailType());
else
textPart.setContent("", MailDetail.TEXT_MAIL);
mp.addBodyPart(textPart);
//add attachments
if (_mailDetail.getAttachments() != null && !_mailDetail.getAttachments().isEmpty())
for (int i = 0, size = _mailDetail.getAttachments().size(); i < size; i++) {
MimeBodyPart attachFilePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource((String) _mailDetail.getAttachments().get(i));
attachFilePart.setDataHandler(new DataHandler(fds));
attachFilePart.setFileName(fds.getName());
mp.addBodyPart(attachFilePart);
}
message.setContent(mp);
}
catch (MessagingException me) {
throw new SystemException("Error setting text: " + _mailDetail.getText(), me, false);
}
//send message
try {
Transport.send(message);
}
catch (MessagingException me) {
throw new SystemException("Error sending e-mail message.", me, false);
}
} //end sendMail
private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
//return new PasswordAuthentication("", "");
}
}
} //end class
asked 09 Oct ‘16, 22:42
Srinivas Yad…
6●1●1●2
accept rate: 0%
closed 10 Oct ‘16, 01:16
Jasper ♦♦
23.8k●5●51●284