I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.
What's a simple, easy way to send an e-mail in Java?
I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.
What's a simple, easy way to send an e-mail in Java?
Here's my code for doing that:
import javax.mail.*;
import javax.mail.internet.*;
// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);
// Construct the message
String to = "you@you.com";
String from = "me@me.com";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Hi,\n\nHow are you?");
// Send the message.
Transport.send(msg);
} catch (MessagingException e) {
// Error.
}
You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/
JavaMail can be a bit of a pain to use. If you want a simpler, cleaner, solution then have a look at the Spring wrapper for JavaMail. The reference docs are here:
http://static.springframework.org/spring/docs/2.5.x/reference/mail.html
However, this does mean you need Spring in your application, if that isn't an option then you could look at another opensource wrapper such as simple-java-mail:
Alternatively, you can use JavaMail directly, but the two solutions above are easier and cleaner ways to send email in Java.
Yet another option that wraps the Java Mail API is Apache's commons-email.
From their User Guide.
SimpleEmail email = new SimpleEmail();
email.setHostName("mail.myserver.com");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setSubject("Test message");
email.setMsg("This is a simple test of commons-email");
email.send();
To followup on jon's reply, here's an example of sending a mail using simple-java-mail.
The idea is that you don't need to know about all the technical (nested) parts that make up an email. In that sense it's a lot like Apache's commons-email, except that Simple Java Mail is a little bit more straightforward than Apache's mailing API when dealing with attachments and embedded images. Spring's mailing facility works as well but is a bit awkward in use (for example it requires an anonymous innerclass) and ofcourse you need to a dependency on Spring which gets you much more than just a simple mailing library, since it its base it was designed to be an IOC solution.
Simple Java Mail btw is a wrapper around the JavaMail API.
final Email email = new Email();
email.setFromAddress("lollypop", "lolly.pop@somemail.com");
email.setSubject("hey");
email.addRecipient("C. Cane", "candycane@candyshop.org", RecipientType.TO);
email.addRecipient("C. Bo", "chocobo@candyshop.org", RecipientType.BCC);
email.setText("We should meet up! ;)");
email.setTextHTML("<img src='cid:wink1'><b>We should meet up!</b><img src='cid:wink2'>");
// embed images and include downloadable attachments
email.addEmbeddedImage("wink1", imageByteArray, "image/png");
email.addEmbeddedImage("wink2", imageDatesource);
email.addAttachment("invitation", pdfByteArray, "application/pdf");
email.addAttachment("dresscode", odfDatasource);
new Mailer("smtp.host.com", 25, "username", "password").sendMail(email);
// or alternatively, pass in your own traditional MailSession object.
new Mailer(preconfiguredMailSession).sendMail(email);
I usually define my javamail session in the GlobalNamingResources section of tomcat's server.xml file so that my code does not depend on the configuration parameters:
<GlobalNamingResources>
<Resource name="mail/Mail" auth="Container" type="javax.mail.Session"
mail.smtp.host="localhost"/>
...
</GlobalNamingResources>
and I get the session via JNDI:
Context context = new InitialContext();
Session sess = (Session) context.lookup("java:comp/env/mail/Mail");
MimeMessage message = new MimeMessage(sess);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject, "UTF-8");
message.setText(content, "UTF-8");
Transport.send(message);
Add java.mail jar into your class path if it is non maven project Add the below dependency into your pom.xml execute the code
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
Below is the tested code
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSendingDemo {
static Properties properties = new Properties();
static {
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
}
public static void main(String[] args) {
String returnStatement = null;
try {
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourEmailId", "password");
}
};
Session session = Session.getInstance(properties, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourEmailId"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("recepeientMailId"));
message.setSentDate(new Date());
message.setSubject("Test Mail");
message.setText("Hi");
returnStatement = "The e-mail was sent successfully";
System.out.println(returnStatement);
Transport.send(message);
} catch (Exception e) {
returnStatement = "error in sending mail";
e.printStackTrace();
}
}
}
use the Java Mail library
import javax.mail.*
...
Session mSession = Session.getDefaultInstance(new Properties());
Transport mTransport = null;
mTransport = mSession.getTransport("smtp");
mTransport.connect(cServer, cUser, cPass);
MimeMessage mMessage = new MimeMessage(mSession);
mTransport.sendMessage(mMessage, mMessage.getAllRecipients());
mTransport.close();
This is a truncated version of the code I use to have an application send emails. Obviously, putting a body and recipients in the message before sending it is probably going to suit you better.
The maven repository location is artifactId: javax.mail, groupId: mail.
Tested Code send Mail with attachment :
public class SendMailNotificationWithAttachment {
public static void mailToSendWithAttachment(String messageTosend, String snapShotFile) {
String to = Constants.MailTo;
String from = Constants.MailFrom;
String host = Constants.smtpHost;// or IP address
String subject = Constants.subject;
// Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
// message.setText(messageTosend);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageTosend);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filepath = snapShotFile;
DataSource source = new FileDataSource(filepath);
messageBodyPart.setDataHandler(new DataHandler(source));
Path p = Paths.get(filepath);
String NameOffile = p.getFileName().toString();
messageBodyPart.setFileName(NameOffile);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
// Log.info("Message is sent Successfully");
// System.out.println("Message is sent Successfully");
System.out.println("Message is sent Successfully");
} catch (MessagingException e) {
// Log.error("Mail sending is Failed " + "due to" + e);
SendMailNotificationWithAttachment smnwa = new SendMailNotificationWithAttachment();
smnwa.mailSendFailed(e);
throw new RuntimeException(e);
}
}
public void mailSendFailed(MessagingException e) {
System.out.println("Mail sending is Failed " + "due to" + e);
Log log = new Log();
log.writeIntoLog("Mail sending is Failed " + "due to" + e.toString(), false);
}
}
Here is the simple Solution
Download these jars: 1. Javamail 2. smtp 3. Java.mail
Copy and paste the below code from [http://javapapers.com/core-java/java-email/][1]
Edit the ToEmail, Username and Password (Gmail User ID and Pwd)
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class sendMail {
static String alertByEmail(String emailMessage){
try{
final String fromEmail = "abc@gmail.com";
final String password = "********"; //fromEmail password
final String toEmail = "xyz@gmail.com";
System.out.println("Email configuration code start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host set by default this
props.put("mail.smtp.port", "587"); //TLS Port you can use 465 insted of 587
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.addRecipient(Message.RecipientType.TO, new
InternetAddress(toEmail));
message.setSubject("ALERT");
message.setText(emailMessage);//here you can write a msg what you want to send... just remove String parameter in alertByEmail method oherwise call parameter
System.out.println("text:"+emailMessage);
Transport.send(message);//here mail sending process start.
System.out.println("Mail Sent Successfully");
}
catch(Exception ex)
{
System.out.println("Mail fail");
System.out.println(ex);
}
return emailMessage;
}
public static void main(String[] args) {
String emailMessage = "This mail is send using java code.Report as a spam";
alertByEmail(emailMessage);
}
}
https://github.com/sumitfadale/java-important-codes/blob/main/Send%20a%20mail%20through%20java
enter code here
Spring Boot - Send email using SMTP.
Step 1: Create Spring Boot Web application, You can use Spring Initializr to create.
Step 2: Add the below dependency in pom.xml.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Step 3: Configure SMTP server detail in Application.properties.
########## SMTP configuration to send out emails ##########
####### Make sure to use the correct SMTP configurations #######
spring.mail.host=mail.madarasa.com.in
spring.mail.port=465
spring.mail.username=support@madarasa.com.in
spring.mail.password=yourmailpassword
# Other properties
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true
# SSL, post 465
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class =
javax.net.ssl.SSLSocketFactory
Step 4: Use below code to email only text message.
Controller
import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.happylearning.email.EmailService;
import com.happylearning.model.MailDTO;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@Autowired
private ObjectMapper mapper;
@PostMapping(value = "/text-mail")
public ResponseEntity<Boolean> sendTextMail(@RequestBody MailDTO mailDTO)
throws MessagingException, JsonMappingException, JsonProcessingException {
emailService.sendTextMail(mailDTO);
return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}
}
Service
import javax.mail.MessagingException;
import org.springframework.web.multipart.MultipartFile;
import com.happylearning.model.MailDTO;
public interface EmailService {
public void sendTextMail(MailDTO mailDTO) throws MessagingException;
}
Service Impl
import java.nio.charset.StandardCharsets;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.happylearning.model.MailDTO;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender emailSender;
@Override
public void sendTextMail(MailDTO mailDTO) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
mimeMessageHelper.setFrom(mailDTO.getFrom());
mimeMessageHelper.setTo(mailDTO.getTo());
mimeMessageHelper.setSubject(mailDTO.getSubject());
mimeMessageHelper.setText(mailDTO.getText());
emailSender.send(message);
}
}
Mail DTO
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MailDTO {
private String to;
private String from;
private String subject;
private String text;
}
Here is the code at Github https://github.com/amarhusain/spring-boot-email