Java Mail寫法

public class SendMail {
 public ReturnValue sendMailList(
  ArrayList mailTo,
  String mailFrom,
  String smtpServer,
  String subject,
  String costomerName,
  String content,
  String user,
  String passwd,
  ArrayList replyTo,
  ArrayList telMailTo,
  String telSubject) {
  
  // create some properties and get the default Session
  Properties props = System.getProperties();
  props.put("mail.smtp.host", smtpServer);
  props.put("mail.smtp.auth", "true");
  MailAuthenticator authenticator = new MailAuthenticator(user, passwd);
  Session session = Session.getInstance(props, (Authenticator)authenticator);
  try {
   for (int i = 0; i < mailTo.size(); i++) {
    String mailto = mailTo.get(i).toString();
    System.out.println("Send mail from: " + mailFrom + " To: " + mailto);
    // create a message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(mailFrom));
    InternetAddress[] address = { new InternetAddress(mailto)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    String preContent = "An entry has been uploaded on the Global Business Solutions Database. Please access: ";
    msg.setText(preContent + content);
    if (replyTo != null && replyTo.size() > 0) {
     InternetAddress[] replyMailTo = new InternetAddress[replyTo.size()];
     for (int j = 0; j < replyTo.size(); j++) {
      replyMailTo[j] = new InternetAddress(replyTo.get(j).toString());
     }
     msg.setReplyTo(replyMailTo);
    }
    // set the Date: header
    msg.setSentDate(new Date());
    // send the message
    Transport.send(msg);
   }
   
   for (int i = 0; ((telMailTo != null) && (i < telMailTo.size())); i++) {
    String mailto = telMailTo.get(i).toString();
    System.out.println("Send telephone mail from: " + mailFrom + " To: " + mailto);
    // create a message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(mailFrom));
    InternetAddress[] address = { new InternetAddress(mailto)};
    
    msg.setRecipients(Message.RecipientType.TO, address);
    
    msg.setSubject("GBS Alert Mail");
    
    String preContent = "/"" + telSubject + "/",/"" + costomerName +"/" /rAn entry has been uploaded on the Global Business Solutions Database. Please access: ";
    
    msg.setText(preContent);
    
    if (replyTo != null && replyTo.size() > 0) {
     InternetAddress[] replyMailTo = new InternetAddress[replyTo.size()];
     for (int j = 0; j < replyTo.size(); j++) {
      replyMailTo[j] = new InternetAddress(replyTo.get(j).toString());
     }
     msg.setReplyTo(replyMailTo);
    }
    // set the Date: header
    msg.setSentDate(new Date());
    // send the message
    Transport.send(msg);
   }
  } catch (MessagingException mex) {
   mex.printStackTrace();
   Exception ex = null;
   if ((ex = mex.getNextException()) != null) {
    ex.printStackTrace();
   }
  }
  return null;
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章