javamail郵件傳送例子

weixin_34162629發表於2015-08-13


public class EmailTask
{
   
    // Session used by the javamail classes
    private Session session;
   
    // List of messages郵件傳送資訊物件列表
    private List<Message> messages = null;
   
    /**構造方法
     * Creates a new EmailTask.
     */
    public EmailTask()
    {
        //郵件傳送入參Properties,用來設定引數
        Properties mailProps = new Properties();
        //郵件伺服器地址:域名或ip
        String host = "smtpscn.test.com";
        //郵件伺服器埠,預設25
        String port = "25";
        //是否開啟TLS方式傳送,1 是,0 否.預設否
        String startTLS = "0";
        //是否驗證證照,1 是,0 否.預設是
        String cert = "0";
        //是否鑑權true false
        String isAuth = "true";
        //鑑權賬號
        final String account = "zWX161496";
        //鑑權密碼
        final String pwd = "Asd123";
        if (host != null && !"".equals(host))
        {
            mailProps.setProperty("mail.smtp.host", host);
        }
        if (port != null && !"".equals(port))
        {
            mailProps.setProperty("mail.smtp.port", port);
        }
        //如果開始TLS方式
        if ("1".equals(startTLS))
        {
            mailProps.setProperty("mail.smtp.starttls.enable", "true");
            //是否驗證證照
            if ("0".equals(cert))
            {
                mailProps.setProperty("mail.smtp.ssl.trust", "*");
            }
        }
        //是否鑑權:true false
        mailProps.setProperty("mail.smtp.auth", isAuth);
       
        // Create the mail session, check authenticator
        session = Session.getInstance(mailProps, new Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(account, pwd);
            }
        });
       
        messages = new LinkedList();
    }
   
    /**傳送一批郵件
     * 如果呼叫該方法,將不會通過單獨起一個執行緒的方式來傳送郵件
     * 好處是如果傳送失敗可以立即返回結果
     * 缺點是不適合頻率較高的操作
     */
    public void sendMessage()
    {
        try
        {
            Iterator<Message> messageIterator = messages.iterator();
            while (messageIterator.hasNext())
            {
               
                Message message = messageIterator.next();
                Transport.send(message);
            }
        }
        catch (MessagingException me)
        {
            //
        }
        catch (Exception e)
        {
            //
        }
    }
   
   
    /**
     * 構造Message
     * @param toName the name of the recipient of this email.
     * @param toEmail the email address of the recipient of this email.
     * @param fromName the name of the sender of this email.
     * @param fromEmail the email address of the sender of this email.
     * @param subject the subject of the email.
     * @param body the body of the email.
     */
    public void addMessage(String toName, String toEmail, String fromName,
            String fromEmail, String subject, String body)
    {
       
        if (toEmail == null || fromEmail == null || subject == null
                || body == null)
        {
            DebugLogFactory.debug(MailTmplTool.class,
                    "Error sending email in EmailTask.java: Invalid fields.");
        }
        else
        {
            try
            {
                Message message = createMessage();
                Address to = null;
                Address from = null;
                if (toName != null)
                {
                    to = new InternetAddress(toEmail, toName);
                }
                else
                {
                    to = new InternetAddress(toEmail);
                }
                if (fromName != null)
                {
                    from = new InternetAddress(fromEmail, fromName);
                }
                else
                {
                    from = new InternetAddress(fromEmail);
                }
                message.setRecipient(Message.RecipientType.TO, to);
                message.setFrom(from);
                message.setSubject(subject);
                message.setSentDate(new Date());
                message.setHeader("Content-Transfer-Encoding", "BASE64");
                message.setContent(body, "text/html;charset=UTF-8");
                messages.add(message);
            }
            catch (Exception e)
            {
                //
            }
        }
    }
   
    /**
     *
     * @return A new JavaMail message.
     */
    public Message createMessage()
    {
        return new MimeMessage(session);
    }
}

 

補充:可以使用多執行緒傳送傳送,好處是不影響主執行緒,可以立即返回。

建立一個連結串列LinkedList(可包裝為郵件傳送工廠),用來存放每個郵件任務物件,啟用幾個執行緒如6個,每次發郵件時,將發郵件任務物件新增到LinkedList,注意枷鎖,並通知所有執行緒啟用notifyall;

當LinkedList有元素時,這些執行緒被啟用,同時從LinkedList取出任務,注意加鎖,本別傳送;

當列表為空時,就掛起wait。

 

相關文章