Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificatePendingAvailableSkipIfAvailableFalse() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    String from = "from@example.com";
    String to = "to@example.com";

    proxy.addCertificateRequest(from);/*www  . j  av a2 s .c om*/

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailetConfig.setInitParameter("skipIfAvailable", "false");

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE + 1, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertTrue(proxy.isUser(from));
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateSigningCertAvailable() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    String from = "test@example.com";
    String to = "to@example.com";

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new FileInputStream("test/resources/testdata/keys/testCertificates.p12"),
            "test".toCharArray());

    SystemServices.getKeyAndCertificateWorkflow().importKeyStore(keyStore, MissingKey.ADD_CERTIFICATE);

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from   www  .j ava  2 s.c o  m*/

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress(from));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    assertFalse(proxy.isUser(from));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(22, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(from));
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom,
        String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost
    String host = ConfigManager.getInstance().getSmtpMailhost();
    String port = ConfigManager.getInstance().getSmtpMailport();
    String password = ConfigManager.getInstance().getSmtpMailpassword();
    String auth = ConfigManager.getInstance().getSmtpMailauth();
    String sender = ConfigManager.getInstance().getSmtpMailuser();

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.user", sender);
    properties.setProperty("mail.smtp.password", password);
    properties.setProperty("mail.smtp.auth", auth);
    properties.setProperty("mail.smtp.port", port);

    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // Create a default MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Set From: header field of the header.
    if (!StringUtils.isBlank(sender)) {
        try {//from  w  w w .ja va 2s . com
            message.setFrom(new InternetAddress(sender));

        } catch (AddressException ex) {
            logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex);
        } catch (MessagingException ex) {
            logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex);
        }

    }

    List<Address> addresses = new ArrayList<Address>();

    String receivers = emails.getReceivers();
    receivers = StringUtils.trim(receivers);

    for (String receiver : receivers.split(";")) {
        if (!StringUtils.isBlank(receiver)) {
            try {
                addresses.add(new InternetAddress(receiver));
            } catch (AddressException ex) {
                logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex);
            } catch (MessagingException ex) {
                logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex);
            }
        }
    }
    Address[] add = new Address[addresses.size()];
    addresses.toArray(add);
    try {
        message.addRecipients(Message.RecipientType.TO, add);

        // Set Subject: header field
        message.setSubject("[Pundit Contact Form]: " + subject);

        // Now set the actual message
        message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n"
                + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text);

    } catch (MessagingException ex) {
        logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex);
    }
    // Send message

    try {
        logger.log(Level.INFO, "Trying to send message to receivers: {0}",
                Arrays.toString(message.getAllRecipients()));
        transport = session.getTransport("smtp");
        transport.connect(host, sender, password);
        transport.sendMessage(message, message.getAllRecipients());
        logger.log(Level.INFO, "Sent messages to all receivers {0}",
                Arrays.toString(message.getAllRecipients()));
    } catch (NoSuchProviderException nspe) {
        logger.log(Level.SEVERE, "Cannot find smtp provider", nspe);
    } catch (MessagingException me) {
        logger.log(Level.SEVERE, "Cannot set transport layer ", me);
    } finally {
        try {

            transport.close();
        } catch (MessagingException ex) {

        } catch (NullPointerException ne) {
        }

    }

}

From source file:com.netspective.commons.message.SendMail.java

public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException,
        MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException {
    if (from == null)
        throw new SendMailNoFromAddressException("No FROM address provided.");

    if (to == null && cc == null && bcc == null)
        throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided.");

    Properties props = System.getProperties();
    props.put("mail.smtp.host", host.getTextValue(vc));

    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage message = new MimeMessage(mailSession);

    if (headers != null) {
        List headersList = headers.getHeaders();
        for (int i = 0; i < headersList.size(); i++) {
            Header header = (Header) headersList.get(i);
            message.setHeader(header.getName(), header.getValue().getTextValue(vc));
        }/*from   w w  w  .  ja  v  a2  s  .  c  o m*/
    }

    message.setFrom(new InternetAddress(from.getTextValue(vc)));

    if (replyTo != null)
        message.setReplyTo(getAddresses(replyTo.getValue(vc)));

    if (to != null)
        message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc)));

    if (cc != null)
        message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc)));

    if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc)));

    if (subject != null)
        message.setSubject(subject.getTextValue(vc));

    if (body != null) {
        StringWriter messageText = new StringWriter();
        body.process(messageText, vc, bodyTemplateVars);
        message.setText(messageText.toString());
    }

    Transport.send(message);
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {

    try {//from ww  w  . j a  v a  2  s  .  c  o m
        log.info("Sending notification email to " + notificationEmailAddress + " from "
                + getEMailProperties().getProperty("mail.smtp.from", "jUDDI"));
        if (session != null && notificationEmailAddress != null) {
            MimeMessage message = new MimeMessage(session);
            InternetAddress address = new InternetAddress(notificationEmailAddress);
            Address[] to = { address };
            message.setRecipients(RecipientType.TO, to);
            message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI")));
            //maybe nice to use a template rather then sending raw xml.
            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            Multipart mp = new MimeMultipart();

            MimeBodyPart content = new MimeBodyPart();
            String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body");

            msg_content = String
                    .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName),
                            StringEscapeUtils.escapeHtml(AppConfig.getConfiguration()
                                    .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                            GetSubscriptionType(body), GetChangeSummary(body));

            content.setContent(msg_content, "text/html; charset=UTF-8;");
            mp.addBodyPart(content);

            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
            attachment.setFileName("uddiNotification.xml");
            mp.addBodyPart(attachment);

            message.setContent(mp);
            message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                    + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey());
            Transport.send(message);
        } else {
            throw new DispositionReportFaultMessage("Session is null!", null);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DispositionReportFaultMessage(e.getMessage(), null);
    }

    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

/**
 * This is the actual java mail execution.
 *
 * @param notification//from  w  w  w.java2  s  .c om
 */
private void send(EmailTemplate notification) {

    String from = notification.getFrom();
    String to = notification.getTo();
    String subject = notification.getSubject();
    String style = notification.getStyle();

    // body of the email is set and all substitutions of variables are made
    String body = notification.getBody();

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server

    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtps.port", smtpPort);
    props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false");

    // if (smtpUseAuth) {
    //
    // props.setProperty("mail.smtp.auth", smtpUseAuth + "");
    // props.setProperty("mail.username", smtpUsername);
    // props.setProperty("mail.password", smtpPassword);
    //
    // }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(props);

    // Create a default MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    try {
        // Set the RFC 822 "From" header field using the
        // value of the InternetAddress.getLocalAddress method.
        message.setFrom(new InternetAddress(from));
        // Add the given addresses to the specified recipient type.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set the "Subject" header field.
        message.setSubject(subject);

        // Sets the given String as this part's content,
        // with a MIME type of "text/html".
        message.setContent(style + body, "text/html");

        if (smtpUseAuth) {
            // Send message
            Transport tr = session.getTransport(smtpProtocol);
            tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);

            message.saveChanges();
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } else {
            Transport.send(message);
        }
    } catch (AddressException e) {
        log.error("Email Exception: Cannot connect to email host: " + smtpHost, e);
    } catch (MessagingException e) {
        log.error("Email Exception: Cannot send email message", e);
    }

}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateMultiThreaded() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    final RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/*from   ww w. j  av  a 2  s.c  om*/

    final MimeMessage message1 = new MimeMessage(MailSession.getDefaultSession());

    message1.setContent("test", "text/plain");
    message1.setFrom(new InternetAddress("from@example.com"));

    final Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("to@example.com"));

    message1.saveChanges();

    final MimeMessage message2 = new MimeMessage(MailSession.getDefaultSession());

    message2.setContent("test", "text/plain");
    message2.setFrom(new InternetAddress("from2@example.com"));

    Callable<Null> callable = new Callable<Null>() {

        @Override
        public Null call() throws Exception {
            MockMail mail1 = new MockMail();

            mail1.setMessage(message1);

            mail1.setRecipients(recipients);

            mail1.setSender(new MailAddress("sender1@example.com"));

            mailet.service(mail1);

            MockMail mail2 = new MockMail();

            mail2.setMessage(message2);

            mail2.setRecipients(recipients);

            mail2.setSender(new MailAddress("sender2@example.com"));

            mailet.service(mail2);

            return null;
        }
    };

    Collection<Future<?>> futures = new LinkedList<Future<?>>();

    for (int i = 0; i < 20; i++) {
        futures.add(executorService.submit(callable));
    }

    for (Future<?> future : futures) {
        future.get();
    }

    assertEquals(INITIAL_KEY_STORE_SIZE + 2, proxy.getKeyAndCertStoreSize());
}

From source file:org.quartz.jobs.ee.mail.SendMailJob.java

protected MimeMessage prepareMimeMessage(MailInfo mailInfo) throws MessagingException {
    Session session = getMailSession(mailInfo);

    MimeMessage mimeMessage = new MimeMessage(session);

    Address[] toAddresses = InternetAddress.parse(mailInfo.getTo());
    mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);

    if (mailInfo.getCc() != null) {
        Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc());
        mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);
    }/*  w  w  w. jav a  2s . c  o m*/

    mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom()));

    if (mailInfo.getReplyTo() != null) {
        mimeMessage.setReplyTo(new InternetAddress[] { new InternetAddress(mailInfo.getReplyTo()) });
    }

    mimeMessage.setSubject(mailInfo.getSubject());

    mimeMessage.setSentDate(new Date());

    setMimeMessageContent(mimeMessage, mailInfo);

    return mimeMessage;
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateInvalidOriginator() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    mailet.init(mailetConfig);/* w  w w  . jav a 2 s  .  c o  m*/

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    String to = "to@example.com";

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress(to));

    mail.setRecipients(recipients);

    mail.setSender(null);

    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
    assertFalse(proxy.isUser(to));

    mailet.service(mail);

    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());

    assertFalse(proxy.isUser(to));
    assertFalse(proxy.isUser(EmailAddressUtils.INVALID_EMAIL));
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void sendMail(MailTransport mailTransport) {
    log.debug("Mail delivery started");
    File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile();
    Properties config = new Properties();

    try {/* ww w.j  a  v  a  2  s.c  o m*/
        config.load(new FileReader(propertyfile));
    } catch (IOException e) {
        log.error(e);
    }

    Session session = Session.getDefaultInstance(config);

    log.debug("Received session");

    MimeMessage message = new MimeMessage(session);

    String to = mailTransport.getTo();
    String from = mailTransport.getFrom();
    String replyTo = mailTransport.getReplyTo();
    String subject = mailTransport.getSubject();
    String html = mailTransport.getHtml();
    String text = mailTransport.getText();

    try {
        Address fromAdr = new InternetAddress(from);
        Address toAdr = new InternetAddress(to);
        Address rplyAdr = new InternetAddress(replyTo);

        message.setSubject(subject);
        message.setFrom(fromAdr);
        message.setRecipient(Message.RecipientType.TO, toAdr);
        message.setReplyTo(new Address[] { rplyAdr });
        message.setSender(fromAdr);
        message.addHeader("Return-path", replyTo);
        message.addHeader("X-TRV-MID", mailTransport.getmId());
        message.addHeader("X-TRV-UID", mailTransport.getuId());

        // Content
        MimeBodyPart messageTextPart = new MimeBodyPart();
        messageTextPart.setText(text);
        messageTextPart.setContent(html, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageTextPart);

        // Put parts in message
        message.setContent(multipart);

        log.debug("Dispatching message");
        Transport.send(message);
        log.debug("Mail delivery ended");
    } catch (MessagingException e) {
        log.error(e);
    }

}