Groovy Code to send email automatically via outlook using attachment



//Please ensure to download javax.activation.jar and mail. jar and under your classpath.

@GrabConfig(systemClassLoader=true, initContextClassLoader=true)
@Grab( 'javax.mail:mail:1.4.7' )

import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.InternetAddress;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;




message = "test groovy mail"
subject = "groovy sent this"
toAddress = "mentioned to address here"
fromAddress = "mentioned from address here"


host = "your host name"        // for eg : inrelaymail.ABC.com"



port = "25"  
body = "Attachment Testing"

filename = "C:\\Sample.txt"

Properties mprops = new Properties();
mprops.setProperty("mail.transport.protocol","smtp");
mprops.setProperty("mail.host",host);
mprops.setProperty("mail.smtp.port",port);

Session lSession = Session.getDefaultInstance(mprops,null);
MimeMessage msg = new MimeMessage(lSession);


//tokenize out the recipients in case they came in as a list
StringTokenizer tok = new StringTokenizer(toAddress,";");
ArrayList emailTos = new ArrayList();
while(tok.hasMoreElements()){
emailTos.add(new InternetAddress(tok.nextElement().toString()));
}
InternetAddress[] to = new InternetAddress[emailTos.size()];
to = (InternetAddress[]) emailTos.toArray(to);
msg.setRecipients(MimeMessage.RecipientType.TO,to);
InternetAddress fromAddr = new InternetAddress(fromAddress);
msg.setFrom(fromAddr);
msg.setFrom(new InternetAddress(fromAddress));
msg.setSubject(subject);
msg.setText(message)


MimeBodyPart messagePart = new MimeBodyPart();

messagePart.setText(body);


MimeBodyPart attachmentPart = new MimeBodyPart();

FileDataSource fileDataSource = new FileDataSource(filename) {

    @Override

    public String getContentType() {

  return "application/octet-stream";

    }

};

attachmentPart.setDataHandler(new DataHandler(fileDataSource));

attachmentPart.setFileName(fileDataSource.getName());


Multipart multipart = new MimeMultipart();



multipart.addBodyPart(messagePart);

multipart.addBodyPart(attachmentPart);

msg.setContent(multipart);

Transport transporter = lSession.getTransport("smtp");
transporter.connect();
transporter.send(msg);

Comments