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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class MailAvecAuthentication {
public static void main(String[] args) {
//juste pour le test
MailAvecAuthentication test=new MailAvecAuthentication();
test.setParams("xxx@gmail.com");
try
{
test.sendMail();
}
catch (Exception ex)
{
}
}
public void sendMail()throws MessagingException{
Message message = new MimeMessage(getSession());
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", ""authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", "smtpServeur");
properties.setProperty("mail.smtp.port", "25");
javax.mail.Session session= Session.getInstance(properties,authenticator);
message.addFrom(new InternetAddress[] { new InternetAddress("admin@gmail.com") });*/
message.addRecipient(RecipientType.TO, new InternetAddress("xxxx@gmail.com"));
message.setSubject("subject");
message.setContent("body", "text/plain");
Transport.send(message);
}
public Session getSession() {
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", smtpServeur);
properties.setProperty("mail.smtp.port", "25");
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "username";
String password = "password";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
} |
Partager