Monday, December 14, 2009

Graphical + Attachment java Email Client

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailClient {

private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_AUTH_USER =
xxx@gmail.com;
private static final String SMTP_AUTH_PWD = "xxx";


public static void main(String[] args) throws Exception {

new SimpleMailWithAttachment().test();

}

public void test() throws Exception {
Properties props = new Properties();

props.put("mail.transport.protocol", "smtp");
props.put("mail.host", SMTP_HOST_NAME);

Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing javamail with attachment");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent("<h1>Check attachment</h1>", "text/html");
MimeBodyPart attachFilePart = new MimeBodyPart();

FileDataSource fds =
new FileDataSource("d:\\TwainExample.java");

attachFilePart.setDataHandler(new DataHandler(fds));
attachFilePart.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
mp.addBodyPart(attachFilePart);
message.setContent(mp);
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("
xxx@yahoo.com"));
transport.connect(SMTP_HOST_NAME, SMTP_AUTH_USER,
SMTP_AUTH_PWD);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}

No comments:

Post a Comment