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
|
public static boolean sendEmail(String[] emailsTo,String objet,String Text,String AttchFile,smtpObject objSmtp)
{
try
{
if(objSmtp !=null)
{
String from = objSmtp.getSmtpSender();
final String username = objSmtp.getSmtpUser() ;
final String password = objSmtp.getSmtpPass();
String host = objSmtp.getSmtpServer() ;
String port =objSmtp.getSmtpPort() ;
String auth = objSmtp.getSmtpAuth() ;
String starttls = objSmtp.getSmtpTLS() ;
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.stmp.user",username);
props.put("mail.smtp.auth", auth);
props.put("mail.smtp.starttls.enable", starttls);
props.put("mail.smtp.password",password);
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.port",port);
Session session = Session.getInstance(props, new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username,password);
}
});
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[emailsTo.length];
for (int i = 0; i < emailsTo.length; i++)
{
addressTo[i] = new InternetAddress(emailsTo[i]);
}
msg.setRecipients(RecipientType.TO, addressTo);
msg.setSubject(objet);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(Text,"text/html; charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//Attachment
if(AttchFile!=null )
{
messageBodyPart = new MimeBodyPart();
File attachementFile = new File(AttchFile);
DataSource source = new FileDataSource(attachementFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachementFile.getName());
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.send(msg);
}
else
{
return false;
}
}
catch (AddressException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
} |
Partager