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 84 85 86 87 88 89 90 91 92
| import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author Seb et Lae
*/
public class EnvoiTLS {
static Properties mailServerProperties;
static Session getMailSession;
static MimeMessage generateMailMessage;
static String login;
static String Pwd;
public boolean generateAndSendEmail(String Aqui,String Votre_mail,String Ch_Votre_Mail) throws AddressException, MessagingException, InterruptedException {
Properties config = new Properties();
try {
config.load(new FileInputStream("config.properties"));
login = config.getProperty("login");
Pwd = config.getProperty("pwd");
} catch (IOException ex) {
ex.printStackTrace();
}
boolean mail_ok = false;
try{
String host = "smtp.gmail.com";
String username = login;
String password = Pwd;
String port = "465";
String to = Aqui;
String subject = "Test d'envoi automatique par Java";
String content = Votre_mail;
InternetAddress[] addresses = InternetAddress.parse(to, true);
InternetAddress fromAddress = new InternetAddress(username);
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", username);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
//System.out.println("creating session");
Session session = Session.getDefaultInstance(props, null);
//System.out.println("creating message");
MimeMessage message = new MimeMessage(session);
message.setText(content);
message.setSubject(subject);
message.setFrom(fromAddress);
message.setRecipients(Message.RecipientType.TO,addresses);
message.setHeader("Disposition-Notification-To",fromAddress.getAddress());
message.setHeader("Return-Receipt-To",fromAddress.getAddress());
FileDataSource fds = new FileDataSource(Ch_Votre_Mail);
message.setDataHandler(new DataHandler(fds));
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
mail_ok = true;
}catch(Exception et){
mail_ok = false;
System.out.println(et.getMessage());
}
finally{
return mail_ok;
}
}
} |
Partager