Example usage for javax.mail.internet MimeMessage setRecipients

List of usage examples for javax.mail.internet MimeMessage setRecipients

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setRecipients.

Prototype

public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Set the specified recipient type to the given addresses.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("usage: java msgmultisend <to> <from> <smtp> true|false");
        return;/*from  w  w w  .  ja  v a  2s.c om*/
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Multipart Test");
        msg.setSentDate(new Date());

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create and fill the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // Use setText(text, charset), to show it off !
        mbp2.setText(msgText2, "us-ascii");

        // create the Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // send the message
        Transport.send(msg);
    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);/*from www .  ja  va  2  s.c  om*/
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        Transport.send(msg);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:msgsendsample.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();//from w  w  w  .j  ava2  s .  c  o  m
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);//from w  ww . ja  va 2  s.  c o  m
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        mbp2.attachFile(filename);

        /*
         * Use the following approach instead of the above line if
         * you want to control the MIME type of the attached file.
         * Normally you should never need to do this.
         *
        FileDataSource fds = new FileDataSource(filename) {
        public String getContentType() {
           return "application/octet-stream";
        }
        };
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());
         */

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        /*
         * If you want to control the Content-Transfer-Encoding
         * of the attached file, do the following.  Normally you
         * should never need to do this.
         *
        msg.saveChanges();
        mbp2.setHeader("Content-Transfer-Encoding", "base64");
         */

        // send the message
        Transport.send(msg);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
}

From source file:gov.nih.nci.protexpress.ui.actions.registration.EmailUtil.java

private static MimeMessage constructMessage(List<String> mailRecipients, String from, String mailSubject)
        throws MessagingException {
    Validate.notEmpty(mailRecipients, "No email recipients are specified");
    if (StringUtils.isEmpty(mailSubject)) {
        LOG.info("No email subject specified");
    }/*from  w  w  w  .j  a va  2 s . c o m*/

    List<Address> addresses = new ArrayList<Address>();
    for (String recipient : mailRecipients) {
        addresses.add(new InternetAddress(recipient));
    }

    MimeMessage message = new MimeMessage(mailSession);
    message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()]));
    message.setFrom(new InternetAddress(from));
    message.setSubject(mailSubject);

    return message;
}

From source file:gov.nih.nci.caarray.util.EmailUtil.java

private static MimeMessage constructMessage(List<String> mailRecipients, String from, String mailSubject)
        throws MessagingException {
    Validate.notEmpty(mailRecipients, "No email recipients are specified");
    if (StringUtils.isEmpty(mailSubject)) {
        LOG.info("No email subject specified");
    }/*from   ww w .  j a v  a 2 s. c o  m*/

    List<Address> addresses = new ArrayList<Address>();
    for (String recipient : mailRecipients) {
        addresses.add(new InternetAddress(recipient));
    }

    MimeMessage message = new MimeMessage(MAILSESSION);
    message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()]));
    message.setFrom(new InternetAddress(from));
    message.setSubject(mailSubject);

    return message;
}

From source file:AmazonSESSample.java

private static RawMessage getRawMessage() throws MessagingException, IOException {
    // JavaMail representation of the message
    Session s = Session.getInstance(new Properties(), null);
    s.setDebug(true);//from w w  w .  j  a  v  a  2 s.c  om
    MimeMessage msg = new MimeMessage(s);

    // Sender and recipient
    msg.setFrom(new InternetAddress("aravind@gofastpay.com"));
    InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") };
    msg.setRecipients(javax.mail.Message.RecipientType.TO, address);
    msg.setSentDate(new Date());
    // Subject
    msg.setSubject(SUBJECT);

    // Add a MIME part to the message
    //MimeMultipart mp = new MimeMultipart();
    Multipart mp = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    //mimeBodyPart.setText(BODY);

    //BodyPart part = new MimeBodyPart();
    //String myText = BODY;
    //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html");
    //part.setText(BODY);
    //mp.addBodyPart(part);
    //msg.setContent(mp);
    mimeBodyPart.setContent(BODY, "text/html");
    mp.addBodyPart(mimeBodyPart);
    msg.setContent(mp);

    // Print the raw email content on the console
    //PrintStream out = System.out;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    //String rawString = out.toString();
    //byte[] bytes = IOUtils.toByteArray(msg.getInputStream());
    //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
    //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes()));

    //byteBuffer.put(bytes);
    //byteBuffer.put(Base64.getEncoder().encode(bytes));
    RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray()));
    return rawMessage;
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {//from w  w w  .j a  va 2  s.  c om

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:org.apache.hupa.server.utils.TestUtils.java

/**
 * Creates a new mime message./*ww  w. ja v a2  s  .co m*/
 * It is possible to specify which parts to create (text, html or both) and
 * the number of attachments
 *
 * @param session
 * @param text
 * @param html
 * @param nfiles
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public static Message createMockMimeMessage(Session session, String text, String html, int nfiles)
        throws MessagingException, IOException {
    ArrayList<FileItem> items = new ArrayList<FileItem>();
    for (int i = 1; i <= nfiles; i++) {
        FileItem fileItem;
        fileItem = TestUtils.createMockFileItem("file_" + i + ".bin");
        items.add(fileItem);
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(MessageUtils.getRecipients("from@dom.com")[0]);
    message.setRecipients(RecipientType.TO, MessageUtils.getRecipients("to@dom.com"));
    message.setRecipients(RecipientType.CC, MessageUtils.getRecipients("cc@dom.com"));
    message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients("bcc@dom.com"));
    message.setSubject("Subject");
    return SendMessageBaseServiceImpl.composeMessage(message, text, html, items);
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Sends an email in text-format in iso-8859-1-encoding
 * //from w w w  .  ja  v a2  s . c om
 * @param subject the subject of the new mail
 * @param message the content of the mail
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendMail(String subject, String message, String from, String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());
        msg.setText(message, "iso-8859-1");
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending mail: " + e.getLocalizedMessage());
    }
}