io farei un thread che rimane attivo fino alla fine della spedizione del ciclo di mail...
un qualcosa del genere...
codice:
// CLASSE PER INVIO MAIL
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class MailHelper{
private String smtpServer = "tuoSMTP";
public boolean sendMail(String from, String to, String subject, String body){
boolean returnValue = false;
try{
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
// -- Set the subject and body text --
msg.setSubject(subject);
String mimeEncoding = MimeUtility.mimeCharset("<Java Char encoding name>");
//msg.setContent(body, "text/html");
String charset = "utf-8";
msg.setContent(body, "text/plain; charset=" + charset);
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
//System.out.println("Message sent OK.");
returnValue = true;
}catch (Exception ex){
returnValue = false;
}
return returnValue;
}
}
codice:
// THREAD CICILICO
public class EsecuzioneProva {
// DICHIARAZIONI VARIABILI E OGGETTI
MailHelper mailHelper = new MailHelper();
// ESECUZIONE PRINCIPALE DEL PROGRAMMA
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run () {
Thread t = Thread.currentThread();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// QUA HAI UN VETTORE DI MAIL DA SPEDIRE ( la classe ClasseMail sarà da creare !! )
for(int i=0;i<tuoVector.size();i++){
String from = (ClasseMail)tuoVector.elementAt(i).getFrom();
String to = (ClasseMail)tuoVector.elementAt(i).getTo();
String subject = (ClasseMail)tuoVector.elementAt(i).getSubject();
String body = (ClasseMail)tuoVector.elementAt(i).getBody();
boolean invioMail = mailHelper.sendMail(from, to, subject, body);
}
}
};
(new Thread (r)).start();
}