1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Envoyer un email
*/
public class SendMail {
private Session session = null;
private Transport transport = null;
/**
* Fixer les propriétés
*/
public void connect(String host, String user, String password) throws NoSuchProviderException, MessagingException {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.put("mail.smtp.auth", "true");
// properties.setProperty("mail.smtp.port", "587");
this.session = Session.getDefaultInstance(properties, null);
this.transport = this.session.getTransport();
this.transport.connect(host, user, password);
}
public void send(String from, String to, String subject, String body) throws MessagingException {
MimeMessage message = new MimeMessage(this.session);
message.setSubject(subject);
message.setContent(body, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(from));
this.transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
this.transport.close();
}
/**
* Exemple pour envoyer un email avec SMTP
*/
public static void main(String args[]) {
try {
SendMail email = new SendMail();
email.connect("smtp.xxx.fr", "xx@FAI.fr", "motdepasse");
email.send("dest@FAI.fr", "from@FAI.fr", "Envoyer un email avec JAVA", "Je suis le corps du message");
} catch (MessagingException ex) {
Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
Partager