javamail郵件發送例子


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

 

補充:能夠使用多線程發送發送,好處是不影響主線程,能夠當即返回。java

建立一個鏈表LinkedList(可包裝爲郵件發送工廠),用來存放每一個郵件任務對象,啓用幾個線程如6個,每次發郵件時,將發郵件任務對象添加到LinkedList,注意枷鎖,並通知全部線程激活notifyall;服務器

當LinkedList有元素時,這些線程被激活,同時從LinkedList取出任務,注意加鎖,本別發送;session

當列表爲空時,就掛起wait。多線程

相關文章
相關標籤/搜索