Ciao, questo codice che sto postando è uno snellimento dell'originale incluso in JavaMail 1.4 tra le demo (smtpsend.java). Funziona con l'autenticazione con yahoo
codice:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class SendMailSMTP {
private String mailer = "SendMailSMTP";
private String prot = "smtps";
private String mailhost = "smtp.mail.yahoo.com";
private boolean auth = true;
private boolean debug = true;
private boolean verbose = false;
private String user = "user_name_su_yahoo";
private String password = "relativa_password";
private String from = "TuoNome Via JavaMail <tuo_indirizzo@yahoo.it>";
private String to = "AltroNome <altro_indirizzo@whatever.com>";
private String subject = "An email from Java Mail";
public SendMailSMTP() throws Exception {
Properties props = System.getProperties();
if (mailhost != null) {
props.put("mail." + prot + ".host", mailhost);
}
if (auth) {
props.put("mail." + prot + ".auth", "true");
}
Session session = Session.getInstance(props, null);
if (debug) {
session.setDebug(true);
}
// construct the message
Message msg = new MimeMessage(session);
if (from != null) {
msg.setFrom(new InternetAddress(from));
}
else {
msg.setFrom();
}
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
/*if (cc != null) {
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc, false));
}
if (bcc != null) {
msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(bcc, false));
}*/
msg.setSubject(subject);
String text = "This message was sent via Java Mail\n Testing the"+
" authentication features of the new version, JavaMail 1.4";
msg.setText(text);
SMTPTransport t =
(SMTPTransport)session.getTransport(prot);
try {
if (auth)
t.connect(mailhost, user, password);
else
t.connect();
t.sendMessage(msg, msg.getAllRecipients());
}
finally {
if (verbose)
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
msg.setHeader("X-Mailer", mailer);
msg.setSentDate(new Date());
System.out.println("\nMail was sent successfully.");
}
public static void main(String[] argv) {
try {
new SendMailSMTP();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
funziona parimenti bene con gmail, ti basta usare la login per un tuo account gmail e modificare
codice:
private String mailhost = "smtp.mail.yahoo.com";
in
codice:
private String mailhost = "smtp.gmail.com";
Ovviamente così come è scritta è una porcata di classe, però dovrebbe darti un'idea di come procedere (vorrai costruttori in grado di accettare quei benedetti parametri di cui all'inizio)