This is our old Q&A Site. Please post any new questions and answers at

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() {

    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.auth", "true");
    this.mailProps.put("mail.smtp.port", "465");

    /*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);
} //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) {
} //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);

        //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);
            try {
            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) {
        } //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) {
    } //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");

    //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 {
    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)
    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());
            textPart.setContent("", MailDetail.TEXT_MAIL);

        //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));

    catch (MessagingException me) {
        throw new SystemException("Error setting text: " + _mailDetail.getText(), me, false);

    //send message
    try {
    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%20Yadadadad's gravatar image

Srinivas Yad...
accept rate: 0%

closed 10 Oct '16, 01:16

Jasper's gravatar image

Jasper ♦♦

The question has been closed for the following reason "Question is off-topic or not relevant. This is a Wireshark Q&A, including packet capture/network analysis. Maybe is a better place for this." by Jasper 10 Oct '16, 01:16

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:


question asked: 09 Oct '16, 22:42

question was seen: 872 times

last updated: 10 Oct '16, 01:16

p​o​w​e​r​e​d by O​S​Q​A