Example code for sending mail with attachments using Java

0

The following code demonstrates how to send a mail with JavaMail . The example code uses the mail.jar file , which is included in the JavaMail download .

/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; /** * * @author amal * version 1.0 */ public class Mailer { public static void main(String[] args) throws Exception{ Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", "mailServer"); properties.setProperty("mail.user", "emailUser"); properties.setProperty("mail.password", "emailPassword"); Session sess = Session.getDefaultInstance(properties, null); Transport transport = sess.getTransport(); MimeMessage message = new MimeMessage(sess); message.setSubject("Mail Subject"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("Mail Content", "text/html"); MimeBodyPart attachmentPart = new MimeBodyPart(); FileDataSource fileDS =new FileDataSource("FileToBeAttached"); attachmentPart.setDataHandler(new DataHandler(fileDS)); attachmentPart.setFileName(fileDS.getName()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); message.addRecipient(Message.RecipientType.TO, new InternetAddress("recepient@domain.com")); transport.connect(); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } }

Read more »

0 comments:

Post a Comment

© Zone817. Powered by Blogger.