Example usage for javax.mail.internet MimeMessage setSentDate

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

Introduction

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

Prototype

@Override
public void setSentDate(Date d) throws MessagingException 

Source Link

Document

Set the RFC 822 "Date" header field.

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.  j ava  2 s .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:msgsendsample.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();/*from w ww  .j  a  v a 2  s. c  om*/
        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  ww w . java 2s .  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: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);//w  ww. j  a  v  a 2 s  .  com
    }

    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:eu.forgestore.ws.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((FStoreRepository.getPropertyByName("mailhost").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", FStoreRepository.getPropertyByName("mailhost").getValue());
    if ((FStoreRepository.getPropertyByName("mailuser").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", FStoreRepository.getPropertyByName("mailuser").getValue());
    if ((FStoreRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", FStoreRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = FStoreRepository.getPropertyByName("adminEmail").getValue();
    String subj = FStoreRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;//from  www .j  a  v a 2s  . c o m
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;//from  w w  w  .ja v  a  2  s.c  om
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:portal.api.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody, String subj) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    if ((PortalRepository.getPropertyByName("mailhost").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", PortalRepository.getPropertyByName("mailhost").getValue());
    if ((PortalRepository.getPropertyByName("mailuser").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", PortalRepository.getPropertyByName("mailuser").getValue());
    if ((PortalRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", PortalRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = PortalRepository.getPropertyByName("adminEmail").getValue();
    final String username = PortalRepository.getPropertyByName("mailuser").getValue();
    final String password = PortalRepository.getPropertyByName("mailpassword").getValue();

    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*w  w w. j  av  a 2  s. c o  m*/
    });

    Transport transport;
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(adminemail, adminemail));

        transport.connect();

        Address[] recips = (Address[]) ArrayUtils.addAll(msg.getRecipients(Message.RecipientType.TO),
                msg.getRecipients(Message.RecipientType.CC));

        transport.sendMessage(msg, recips);

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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);//  w w w  .j a v a 2 s.  c  o  m
    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:org.latticesoft.util.resource.MessageUtil.java

/**
 * Sends the email.//from  w w  w. ja  v a2s. co m
 * @param info the EmailInfo containing the message and other details
 * @param p the properties to set in the environment when instantiating the session
 * @param auth the authenticator
 */
public static void sendMail(EmailInfo info, Properties p, Authenticator auth) {
    try {
        if (p == null) {
            if (log.isErrorEnabled()) {
                log.error("Null properties!");
            }
            return;
        }
        Session session = Session.getInstance(p, auth);
        session.setDebug(true);
        if (log.isInfoEnabled()) {
            log.info(p);
            log.info(session);
        }
        MimeMessage mimeMessage = new MimeMessage(session);
        if (log.isInfoEnabled()) {
            log.info(mimeMessage);
            log.info(info.getFromAddress());
        }
        mimeMessage.setFrom(info.getFromAddress());
        mimeMessage.setSentDate(new Date());
        List l = info.getToList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                if (log.isInfoEnabled()) {
                    log.info(addr);
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, addr);
            }
        }
        l = info.getCcList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.CC, addr);
            }
        }
        l = info.getBccList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.BCC, addr);
            }
        }

        if (info.getAttachment().size() == 0) {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
                mimeMessage.setText(info.getContent(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
                mimeMessage.setText(info.getContent());
            }
            mimeMessage.setContent(info.getContent(), info.getContentType());
        } else {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            if (info.getCharSet() != null) {
                body.setText(info.getContent(), info.getCharSet());
                body.setContent(info.getContent(), info.getContentType());
            } else {
                body.setText(info.getContent());
                body.setContent(info.getContent(), info.getContentType());
            }
            mp.addBodyPart(body);
            for (int i = 0; i < info.getAttachment().size(); i++) {
                String filename = (String) info.getAttachment().get(i);
                MimeBodyPart attachment = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                attachment.setDataHandler(new DataHandler(fds));
                attachment.setFileName(MimeUtility.encodeWord(fds.getName()));
                mp.addBodyPart(attachment);
            }
            mimeMessage.setContent(mp);
        }
        Transport.send(mimeMessage);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in sending email", e);
        }
    }
}

From source file:mitm.common.tools.SendMail.java

private static void prepareMessage(MimeMessage message, String from, String subject) throws MessagingException {
    message.setSentDate(new Date());

    if (from != null) {
        message.setFrom(new InternetAddress(from));
    }//from w ww  . ja  va  2s . co m

    if (subject != null) {
        message.setSubject(subject);
    }
}