Wednesday, March 30, 2011

Send email in Java with attachment

//javax.mail API is required to work with this code
//send email in Java from Gmail account with attachments

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailWithAttachment
{
public static void main(String args[]) throws Exception
{
    String host = "smtp.gmail.com";//host name
    String from = "abc@gmail.com";//sender id
    String to = "xyz@yahoo.com";//reciever id
    String pass = "***";//sender's password
    String fileAttachment = "test.txt";//file name for attachment
    //system properties
    Properties prop = System.getProperties();
    // Setup mail server properties
    prop.put("mail.smtp.gmail", host);
    prop.put("mail.smtp.starttls.enable", "true");
    prop.put("mail.smtp.host", host);
    prop.put("mail.smtp.user", from);
    prop.put("mail.smtp.password", pass);
    prop.put("mail.smtp.port", "587");
    prop.put("mail.smtp.auth", "true");
    //session
    Session session = Session.getInstance(prop, null);
    // Define message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
    message.setSubject("Hello Java Mail Attachment");
    // create the message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    //message body
    messageBodyPart.setText("Hi");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    //attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(fileAttachment);
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    //send message to reciever
    Transport transport = session.getTransport("smtp");
    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}
}

21 comments:

  1. Thanks brother from Colombia!.Yes Lationamerica.

    ReplyDelete
  2. Replies
    1. you should provide full path of the file if ur file is outside the project director.

      Delete
  3. i am getting this runtime exception
    Exception in thread "main" javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. i1sm4525823pbv.49

    at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:879)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:599)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:319)
    at com.preflight.mail.Javamail6.main(Javamail6.java:63)
    Java Result: 1

    ReplyDelete
    Replies
    1. Please verify if your email address is correct in your Mail preferences

      (String from = "abc@gmail.com";//sender id
      String to = "xyz@yahoo.com";//reciever id)

      edit these both strings and provide some valid email addresses.

      and try again.

      Delete
  4. Thank you very much , your code is awesome...

    ReplyDelete
  5. I am having error while adding the attachment..

    Exception in thread "main" java.lang.NullPointerException
    at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:226)
    at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:299)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1375)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
    at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
    at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1354)
    at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107)
    at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075)
    at javax.mail.Transport.send(Transport.java:123)
    at DAO.SendMailTLS.main(SendMailTLS.java:95)

    the file is in the same directory, and i have tried with the full path also. plz suggest ...

    ReplyDelete
    Replies
    1. You are getting a NullPointerException which means either you have not initialized any of parameter or you have to use try-catch around a statement which throws this exception.

      Delete
  6. Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: com/sun/mail/util/SharedByteArrayInputStream
    at AttachExample.sendMail(AttachExample.java:27)
    at ExpansionDetails$4.actionPerformed(ExpansionDetails.java:424)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.SharedByteArrayInputStream
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 38 more

    ReplyDelete
  7. I just used sendMail method instead of main...

    ReplyDelete
    Replies
    1. @ Aniketk u should try the same code first to get idea how does it works and then u can use it in ur GUI which u r developing. i think u have just messed up the things.

      Delete
  8. Hi..
    I am getting this error. I m able to run on my laptop but when i try on my company's desktop, its giving me an error

    Exception in thread "main" javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1704)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
    at MailWithAttachment.main(MailWithAttachment.java:52)
    Caused by: java.net.UnknownHostException: smtp.gmail.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at java.net.Socket.connect(Socket.java:469)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
    ... 4 more

    Can someone plz assist me in this.

    ReplyDelete
  9. I have found code for adding attachment in new and existing email at the documentation page of Aspose.Email for Java Below is the code:

    Adding Attachments to a New Email Message


    //Create an instance of MailMessage class
    MailMessage message = new MailMessage();

    //From
    message.setFrom(new MailAddress("sender@sender.com"));

    //to whom
    message.getTo().add(new MailAddress("receiver@gmail.com"));

    //Adding 1st attachment
    //Create an instance of Attachment class
    Attachment attachment;

    //Load an attachment
    attachment = new Attachment("1.txt");

    //Add attachment in instance of MailMessage class
    message.getAttachments().add(attachment);

    //Add 2nd Attachment
    message.getAttachments().add(new Attachment("1.jpg"));

    //Add 3rd Attachment
    message.getAttachments().add(new Attachment("1.doc"));

    //Add 4th Attachment
    message.getAttachments().add(new Attachment("1.rar"));

    //Add 5th Attachment
    message.getAttachments().add(new Attachment("1.pdf"));

    //Save message to disc
    message.save("output.msg",MessageFormat.getMsg());


    Extract Attachments from an existing Email Message


    publicstatic void main(String[] args)
    {
    // Base folder for reading and writing files
    StringstrBaseFolder = "D:\\Data\\Aspose\\resources\\";

    //Initialize and Load an existing EML file by specifying the MessageFormat
    MailMessagemsg = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());

    //Initialize AttachmentCollection object with MailMessage Attachments
    AttachmentCollection attachments = msg.getAttachments();

    //Iterate over the AttachmentCollection
    for(int index = 0; index 0)
    {
    //Remove Attachment from index location 0
    attachments.remove(0);
    System.out.println("Attachment Count: " + attachments.size());
    }

    //Add a PDF file as Attachment to the message
    message.addAttachment(new Attachment(strBaseFolder + "Blank.PDF"));
    System.out.println("Attachment Count: " + attachments.size());

    //Save the Email message to disk by specifying the EML MailMessageSaveType
    message.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());
    }


    ReplyDelete
  10. Hi I am getting the below expection in the appserver log when trigger an email.
    Can any one help me in identifying the issue.

    PSAPPSRV.15807 (559) [08/22/13 19:59:22 1558233@ohtwbgd21d1-ns-snip.netd.vzwcorp
    .com (IE 8.0; WIN7) ICPanel](0) Rowset::Refresh in program AUC_ANALYZE_HD_CMP.GB
    L.AUC_LINE_WRK.AUC_ANALYZE_PB.FieldChange flushes current or parent scroll
    PSAPPSRV.15807 (559) [08/22/13 19:59:23 1558233@ohtwbgd21d1-ns-snip.netd.vzwcorp
    .com (IE 8.0; WIN7) ICPanel](0) (MCFSendMail): Creating SendMailException
    PSAPPSRV.15807 (559) [08/22/13 19:59:23 1558233@ohtwbgd21d1-ns-snip.netd.vzwcorp
    .com (IE 8.0; WIN7) ICPanel](0) (MCFSendMail): SendMailException
    PSAPPSRV.15807 (559) [08/22/13 19:59:23 1558233@ohtwbgd21d1-ns-snip.netd.vzwcorp
    .com (IE 8.0; WIN7) ICPanel](0) (MCFSendMail): SendMailException: Context: Outbo
    undEmail.Send method called
    PSAPPSRV.15807 (559) [08/22/13 19:59:23 1558233@ohtwbgd21d1-ns-snip.netd.vzwcorp
    .com (IE 8.0; WIN7) ICPanel](0) (MCFSendMail): SendMailException: Java Exception
    : java.lang.NullPointerException
    PSAPPSRV.15807 (559) [08/22/13 19:59:23 1558233@ohtwbgd21d1-ns-snip.netd.vzwcorp
    .com (IE 8.0; WIN7) ICPanel](0) (MCFSendMail): SendMailException: Detail Message
    :JavaMail Error: java.lang.NullPointerException.\nStack Trace:\njava.lang.NullPo
    interException
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:599)
    at com.peoplesoft.pt.mcf.mail.MCFOutboundEmail.send(MCFOutboundEmail.jav
    a:780)
    at com.peoplesoft.pt.mcf.mail.MCFOutboundEmail.send(MCFOutboundEmail.jav
    a:948)

    ReplyDelete
  11. Hi
    Anyone get a chance to looking the above mentioned issue.
    Regards,
    Siva.

    ReplyDelete
    Replies
    1. You are getting a NullPointerException which means either you have not initialized any of parameter. all the best

      Delete
  12. Thanks Friend Its Working good....

    ReplyDelete
  13. I am getting an error for transport.connect(host, from, pass). Can anyone give a solution for this..?
    Thanks.. :)

    ReplyDelete