Overview
This article will demonstrate how to send an email message that includes a file attachment using the components provided in Secure iNet Factory.
To see what else Secure iNet Factory has to offer Download a FREE 30 day Secure iNet Factory Evaluation.
Prerequisites
- SMTP account and server details
- JDK 1.4 or above
- Secure iNet Factory
Sending Email with Attachments using the Smtp Class
The Smtp class provides an easy to use programming interface for communicating with SMTP (Simple Mail Transport Protocol) servers.
There are two ways to define a class that will use the Smtp class. If you want to listen to events fired by the Smtp instance you could have your class implement the SmtpListener interface or extend the SmtpAdapter class, which already implements SmtpListener and provide a default implementation.
//import the necessary interface/class
import com.jscape.inet.smtp.SmtpAdapter;
public class SmtpAttachmentTutorial extends SmtpAdapter {
…
}
Or if not interested on listening to Smtp events then a plain Java class will do.
public class SmtpAttachmentTutorial {
…
}
The following code snippet illustrates the steps needed to compose an email message including attaching a file then connecting to an SMTP server and sending the email.
import java.io.File;
import java.io.IOException;
import com.jscape.inet.smtp.Smtp;
import com.jscape.inet.smtp.SmtpException;
import com.jscape.inet.mime.Attachment;
import com.jscape.inet.mime.MimeException;
import com.jscape.inet.email.EmailMessage;
…
public void sendMessage(String hostname, String to, String from, String subject, String body, String attachment)
throws SmtpException,
IOException,
MimeException
{
// create new Smtp instance
Smtp smtp = new Smtp(hostname);
// enable debugging ... all output is sent to System.out
smtp.setDebug(true);
// capture SMTP related events
smtp.addSmtpListener(this);
// connect to mail server
smtp.connect();
// create new email message
EmailMessage email = new EmailMessage();
// set recipient address
email.setTo(to);
// set from address
email.setFrom(from);
// set subject
email.setSubject(subject);
// set body
email.setBody(body);
// add file attachment to message
email.addAttachment(new Attachment(new File(attachment)));
// send email message
smtp.send(email);
// disconnect from SMTP server
smtp.disconnect();
}
…
Download the complete source code here: SmtpAttachmentTutorial.java
Summary
The requirement for sending emails within an application is very common, from sending registration confirmation to periodic email notifications and some cases it is necessary to attach files on these emails. Using the Secure iNet Factory components adding file attachments to your outbound email messages is a very simple task.
References
Comments