无法发送电子邮件

时间:2016-10-05 11:00:16

标签: java smtp

当我重新启动服务器时,Java电子邮件正在被触发,几天后我的应用程序无法发送电子邮件。

  

错误:连接被拒绝,无法连接到smtp localhost:465

我已经尝试了所有可能的解决方案,但无法解决问题。

package com.er.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.er.exceptions.SystemException;
import com.er.utils.Constants;
import com.er.utils.HelperFunctions;
import com.er.utils.LogHelper;

public class MailHandler implements Runnable {
    private static MailHandler instance = new MailHandler();
    private List<Object> mails = null;
    private static final long INTERVAL = 60000;
    private Properties mailProps = null;
    private MailHandler() {
        super();
        this.mails = new ArrayList<Object>(1);
        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");      

        Thread mailThread = new Thread(this);
        mailThread.start();
    } //end constructor

    public static MailHandler getInstance() {
        return instance;
    } //end getInstance
    public void addMail(MailDetail _mailDetail) {
        synchronized (this.mails) {
            this.mails.add(_mailDetail);
        }
    } //end addMail

    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


    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

    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 (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);
        }


        Session session = Session.getInstance(this.mailProps, new SMTPAuthenticator());

     MimeMessage message = new MimeMessage(session);

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


        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("abc", "abc123");
        }
    }

}

0 个答案:

没有答案