Saturday, 7 May 2022

Send mail using Java Mail

                 import javax.activation.DataHandler;

        import javax.activation.DataSource;

        import javax.activation.FileDataSource;

        import javax.mail.BodyPart;

        import javax.mail.Message;

        import javax.mail.MessagingException;

        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 static void main(String[] args) {

      String to = "to mail address";

      String from = "from mail address";

      String host = "mail host";

      Properties properties = System.getProperties();

      properties.setProperty("mail.smtp.host", host);

      Session session = Session.getDefaultInstance(properties);


      try {

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.addRecipient(Message.RecipientType.TO, new                                 InternetAddress(to));

        message.setSubject("This is the Subject Line!");

         

        BodyPart messageBodyPart = new MimeBodyPart();

         

        messageBodyPart.setText("This is message body");

         

        Multipart multipart = new MimeMultipart();

         

        multipart.addBodyPart(messageBodyPart);

         

        messageBodyPart = new MimeBodyPart();

        String filename = "filePath";

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

         

        message.setContent(multipart);

         

        Transport.send(message);

        System.out.println("Sent message successfully....");

      } catch (MessagingException mex) {

        mex.printStackTrace();

      }

  }

No comments:

Post a Comment

Switch case in Java

 Problem statement: Return the capital of a state based on input state          public String getCapital(String state){               switch...