Sending Mail And Attachments With SMPT Server Using JAVA

First You have to read the file or image as byte array using the Path class which is introduced in java 1.7.
 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
package com.main;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.mail.MessagingException;

public class ByteToImage {

	public static void main(String[] args) throws IOException, MessagingException {

		String outPath = "where the file is to create(Out file Path)";
		String inPath = "file resource path";
		String outFileName = "outDoc.docx";
		String mailId = "Your MailId";
		Path path = Paths.get(inPath);
		byte[] bytes = Files.readAllBytes(path);
		
		FileOutputStream fileOutputStream = new FileOutputStream(outPath);
		fileOutputStream.write(bytes);
		fileOutputStream.close();
		
		EmailUtil util = new EmailUtil();
		util.sendEmail(mailId, "Main First Mail", outFileName, bytes);
		
		System.out.println("File written successfully");

	}

}
After that you have to configure the SMTP server details. And the session object for that SMTP.
 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
	private static Session getSession() {
		String user = "UserName";
		String password = "Password";
		try {
			Properties mailProps = new Properties();

			mailProps.put("mail.smtp.host", "hostmail");
			mailProps.put("mail.smtp.port", "port Number");
			mailProps.put("mail.from", "From Mail");
			mailProps.put("mail.smtp.timeout", "in number");
			mailProps.put("mail.smtp.connectiontimeout", "in number");
			mailProps.put("mail.smtp.auth", "true or false only one is required");
			mailProps.put("mail.smtp.ssl.protocols", "TLSv1.2");  
			mailProps.put("mail.smtp.starttls.enable", "true");
			mailProps.put("mail.smtp.ssl.trust", "you have to trust");

			Authenticator authenticator = new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(user, password);
				}
			};

			Session mailSession = Session.getDefaultInstance(mailProps,
					authenticator);

			return mailSession;
		} catch (Exception ex) {

		}
		return null;
	}
And then send the mail.
 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
public static void sendEmail(String to, String subject, String filename,
			byte[] bytes) throws MessagingException {

		Session mailSession = getSession();

		if (mailSession != null) {
			MimeMessage message = new MimeMessage(mailSession);
			try {
				message.setFrom(new InternetAddress(mailSession
						.getProperty("mail.from")));
				message.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(to, false));
				message.setSubject(subject);
				message.setSentDate(new Date());

				BodyPart bodyPart = new MimeBodyPart();
				bodyPart.setText("Testing mail!......");

				Multipart multipart = new MimeMultipart();
				multipart.addBodyPart(bodyPart);

				// Part two is attachment
				bodyPart = new MimeBodyPart();

				DataSource source = new ByteArrayDataSource(bytes,
						"application/octet-stream");
				bodyPart.setDataHandler(new DataHandler(source));
				bodyPart.setFileName(filename);
				multipart.addBodyPart(bodyPart);
				message.setContent(multipart);
				Transport.send(message);
				System.out.println(" EMAIL SENT SUCCESSFULLY ..!");
			} catch (MessagingException ex) {
				System.out.println(" ERROR WHILE SENDING EMAIL:"
						+ ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
You have to run the java with 2 jars those are mail and activation download jars here

Comments