How to send Emai using Java-SMTP (With images and Attachments)

 Dependency:

<dependency>
         <groupId>com.sun.mail</groupId>
         <artifactId>javax.mail</artifactId>
        <version>1.4.4</version>
</dependency>

Code:

import java.util.Date;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMutipart;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

Pubic void SendEmail(){
 Properties prop = new Properties();
props.put("mail.smtp.host", Your_hostname);
props.put("mail.smtp.port", Your_port);
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
//Set Email address from where you want to send email(Example: XYZ@gmail.com) message.setFrom(new InternetAddress("XYZ@gmail.com"); 


//Set Email address to which you want to send email(Example: ABC@gmail.com) message.setRecipient(Recipient.TO, new InternetAddress("ABC@gmail.com")); 

//set subject 

message.setSubject("This is subject");

//select file that you want to attach to email
String file = "YOUR_filepath";
String filename = "Attachment.txt";

DataSource source = new FileDataSource(file);

MimeMutipart mutipart = new  MimeMutipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
BodyPart messageBodyPart1 = new MimeBodyPart();

String htmlText;

htmlText = "<p> Hi Dikshita,</p>";
htmlText +=  "<p> This is a test Email,</p>" + ",</br>";

htmlText +=  "<div><img src="cid:img1"></div>";

messageBodyPart.setContent(htmText, "Text/html");

//Add image in email body
mutipart.addBodyPart(messageBodyPart);
DataSource img1 = new FileDataSource("Your_Image_Path");
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(img1));
messageBodyPart.setHeader("Content-ID", "<img1>");
messageBodyPart.setHeader("Content-type", "image/jpeg");
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");

messageBodyPart.setDisposition(MimeBodyPart.INLINE);

//attachment
messageBodyPart1.setDataHandler(new DataHandler(source));
messageBodyPart1.setFileName(filename);

mutipart.addBodyPart(messageBodyPart1);

mutipart.addBodyPart(messageBodyPart);
message.setContent(mutipart);

message.setSentDate(new Date());

Transport t = session.getTransport("smtp");

try{
t.connect();
Transport.send(message);
}finally{
t.close();

}

Comments

Popular Posts