My linux world » Java – sendmail

Java - sendmail


Dependencies

If you use maven, add this to your pom.xml :

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-email</artifactId>
  <version>${common-email.version}</version>
</dependency>

Send an email

// Parameters :
String smtpHost = "localhost";
int smtpPort    = 587;
boolean smtpIsSecure    = true;
 
String emailFrom = "emailFrom@example.com";
String emailTo = "emailTo@example.com";
String emailSubject = "subject";
String emailMessage = "Hello world !";
 
// send email :
Email email = new SimpleEmail();
 
if(smtpIsSecure){			
  email.setSslSmtpPort(properties.getProperty(SMTP_PORT));
}
else {
  email.setSmtpPort(smtpPort);	
}
 
email.setHostName(smtpHost);		
email.setAuthenticator(new DefaultAuthenticator("SMTP_USERNAME", "SMTP_PASSWORD"));
email.setSSLOnConnect(smtpIsSecure);
email.setFrom(emailFrom);
email.setSubject(emailSubject);
email.setMsg(emailMessage);
email.addTo(emailTo);
email.send();

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.