Example usage for javax.mail.internet InternetAddress InternetAddress

List of usage examples for javax.mail.internet InternetAddress InternetAddress

Introduction

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

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java

private void sendIcalMessage() throws Exception {

    log.debug("sendIcalMessage");

    // Evaluating Configuration Data
    String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value();
    String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value();
    // String from = "openmeetings@xmlcrm.org";
    String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value();

    String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value();
    String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort);

    Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable");
    if (conf != null) {
        if (conf.getConf_value().equals("1")) {
            props.put("mail.smtp.starttls.enable", "true");
        }//  w w w  .  j a  va2  s  . c  om
    }

    // Check for Authentification
    Session session = null;
    if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null
            && emailUserpass.length() > 0) {
        // use SMTP Authentication
        props.put("mail.smtp.auth", "true");
        session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass));
    } else {
        // not use SMTP Authentication
        session = Session.getDefaultInstance(props, null);
    }

    // Building MimeMessage
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setSubject(subject);
    mimeMessage.setFrom(new InternetAddress(from));
    mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

    // -- Create a new message --
    BodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\"")));

    Multipart multipart = new MimeMultipart();

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource(
            new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    iCalAttachment.setFileName("invite.ics");

    multipart.addBodyPart(iCalAttachment);
    multipart.addBodyPart(msg);

    mimeMessage.setSentDate(new Date());
    mimeMessage.setContent(multipart);

    // -- Set some other header information --
    // mimeMessage.setHeader("X-Mailer", "XML-Mail");
    // mimeMessage.setSentDate(new Date());

    // Transport trans = session.getTransport("smtp");
    Transport.send(mimeMessage);

}

From source file:eu.scape_project.planning.user.Groups.java

/**
 * Sends an invitation mail to the user.
 * /*from  w  w w. j av  a  2 s .c o  m*/
 * @param toUser
 *            the recipient of the mail
 * @param serverString
 *            the server string
 * @return true if the mail was sent successfully, false otherwise
 * @throws InvitationMailException
 *             if the invitation mail could not be send
 */
private void sendInvitationMail(GroupInvitation invitation, String serverString)
        throws InvitationMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail()));
        message.setSubject(
                user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName());

        StringBuilder builder = new StringBuilder();
        builder.append("Hello, \n\n");
        builder.append("The Plato user " + user.getFullName() + " has invited you to join the group "
                + user.getUserGroup().getName() + ".\n\n");
        builder.append(
                "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://"
                        + serverString + "/idp/addUser.jsf.\n");
        builder.append(
                "If you have an account, please log in and use the following link to accept the invitation: \n");
        builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid="
                + invitation.getInvitationActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Group invitation mail sent successfully to " + invitation.getEmail());

    } catch (MessagingException e) {
        log.error("Error sending group invitation mail to " + invitation.getEmail(), e);
        throw new InvitationMailException(e);
    }
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Get sender address./*from  w ww  .j ava 2s . c  o  m*/
 * 
 * @return sender address.
 * @throws AddressException 
 * @throws LDAPException 
 */
private InternetAddress getFromAddress() throws AddressException, LDAPException {
    if (from != null) {
        return new InternetAddress(from);
    }
    return new InternetAddress(getUserEmail());
}

From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java

/**
 * ??/*from ww  w .  ja  v a2 s  .c o m*/
 * 
 * @param config javelin.properties???
 * @param entry ??
 * @return ???
 * @throws MessagingException ??????
 */
protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry)
        throws MessagingException {
    // JavaMail???
    Properties props = System.getProperties();
    String smtpServer = this.config_.getSmtpServer();
    if (smtpServer == null || smtpServer.length() == 0) {
        LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED);
        String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified";
        String messageDetail = CommunicatorMessages.getMessage(detailMessageKey);

        throw new MessagingException(messageDetail);
    }
    props.setProperty(SMTP_HOST_KEY, smtpServer);
    int smtpPort = config.getSmtpPort();
    props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort));

    // ???????
    Session session = null;
    if (authenticator_ == null) {
        // ?????
        session = Session.getDefaultInstance(props);
    } else {
        // ???
        props.setProperty(SMTP_AUTH_KEY, "true");
        session = Session.getDefaultInstance(props, authenticator_);
    }

    // MIME??
    MimeMessage message = new MimeMessage(session);

    // ??
    // :
    Date date = new Date();
    String encoding = this.config_.getSmtpEncoding();
    message.setHeader("X-Mailer", X_MAILER);
    message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\"");
    message.setSentDate(date);

    // :from
    String from = this.config_.getSmtpFrom();
    InternetAddress fromAddr = new InternetAddress(from);
    message.setFrom(fromAddr);

    // :to
    String[] recipients = this.config_.getSmtpTo().split(",");
    for (String toStr : recipients) {
        InternetAddress toAddr = new InternetAddress(toStr);
        message.addRecipient(Message.RecipientType.TO, toAddr);
    }

    // :body, subject
    String subject;
    String body;
    subject = createSubject(entry, date);
    try {
        body = createBody(entry, date);
    } catch (IOException ex) {
        LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, "");
        body = createDefaultBody(entry, date);
    }

    message.setSubject(subject, encoding);
    message.setText(body, encoding);

    return message;
}

From source file:TestOpenMailRelay.java

/** Do the work: send the mail to the SMTP server.  */
public void doSend() {

    // We need to pass info to the mail server as a Properties, since
    // JavaMail (wisely) allows room for LOTS of properties...
    Properties props = new Properties();

    // Your LAN must define the local SMTP server as "mailhost"
    // for this simple-minded version to be able to send mail...
    props.put("mail.smtp.host", "mailhost");

    // Create the Session object
    session = Session.getDefaultInstance(props, null);
    session.setDebug(true); // Verbose!

    try {//from  w w  w. jav a 2 s  .c o m
        // create a message
        mesg = new MimeMessage(session);

        // From Address - this should come from a Properties...
        mesg.setFrom(new InternetAddress("nobody@host.domain"));

        // TO Address 
        InternetAddress toAddress = new InternetAddress(message_recip);
        mesg.addRecipient(Message.RecipientType.TO, toAddress);

        // CC Address
        InternetAddress ccAddress = new InternetAddress(message_cc);
        mesg.addRecipient(Message.RecipientType.CC, ccAddress);

        // The Subject
        mesg.setSubject(message_subject);

        // Now the message body.
        mesg.setText(message_body);
        // XXX I18N: use setText(msgText.getText(), charset)

        // Finally, send the message!
        Transport.send(mesg);

    } catch (MessagingException ex) {
        while ((ex = (MessagingException) ex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:ch.dbs.actions.reports.ILVReport.java

/**
 * Send an email with attached PDF as ILL order (ILV-Bestellung).
 *///from   w  w w.  j  a  v a 2s .co m
public ActionForward sendIlvMail(final ActionMapping mp, final ActionForm fm, final HttpServletRequest rq,
        final HttpServletResponse rp) {

    final Auth auth = new Auth();
    // make sure the user is logged in
    if (!auth.isLogin(rq)) {
        return mp.findForward(Result.ERROR_TIMEOUT.getValue());
    }
    // check access rights
    if (!auth.isBibliothekar(rq) && !auth.isAdmin(rq)) {
        return mp.findForward(Result.ERROR_MISSING_RIGHTS.getValue());
    }
    // if activated on system level, access will be restricted to paid only
    if (auth.isPaidOnly(rq)) {
        return mp.findForward(Result.ERROR_PAID_ONLY.getValue());
    }

    String forward = Result.FAILURE.getValue();

    final IlvReportForm ilvf = (IlvReportForm) fm;
    final UserInfo ui = (UserInfo) rq.getSession().getAttribute("userinfo");
    final Check check = new Check();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

        // validate email: failing mails would be returned to the system email and not
        // to the library generating the invalid email!
        if (check.isEmail(ilvf.getTo())) {

            // prepare attachment
            DataSource aAttachment = null;

            // create PDF report using the appropriate ILL form number
            runReport(ilvf, ui, baos);

            aAttachment = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");

            // prepare email
            final InternetAddress[] to = new InternetAddress[2];
            to[0] = new InternetAddress(ilvf.getTo());
            to[1] = new InternetAddress(ui.getKonto().getDbsmail());

            // Create and send email
            final MHelper mh = new MHelper(to, ilvf.getSubject(), composeMailBody(ui, ilvf), aAttachment,
                    composeFilename(ilvf, ui));
            mh.setReplyTo(ui.getKonto().getDbsmail());
            mh.send();

            forward = Result.SUCCESS.getValue();
            final String content = "ilvmail.confirmation";
            final String link = "listkontobestellungen.do?method=overview";
            final ch.dbs.form.Message mes = new ch.dbs.form.Message(content, link);
            rq.setAttribute("message", mes);
            rq.setAttribute("IlvReportForm", ilvf);

        } else {
            final ErrorMessage em = new ErrorMessage("error.email", "listkontobestellungen.do?method=overview");
            rq.setAttribute(Result.ERRORMESSAGE.getValue(), em);
        }
    } catch (final JRException e1) {
        final ErrorMessage em = new ErrorMessage("error.createilvreport",
                "listkontobestellungen.do?method=overview");
        rq.setAttribute(Result.ERRORMESSAGE.getValue(), em);
    } catch (final Exception e) {
        final ErrorMessage em = new ErrorMessage("error.sendmail", e.getMessage(),
                "listkontobestellungen.do?method=overview");
        rq.setAttribute(Result.ERRORMESSAGE.getValue(), em);
    } finally {
        try {
            baos.close();
        } catch (final IOException e) {
            LOG.error(e.toString());
        }
    }

    return mp.findForward(forward);
}

From source file:edu.stanford.muse.util.JSONUtils.java

private static Address[] convertStringsToInternetAddrs(List<String> list) throws AddressException {
    Address[] result = new Address[list.size()];
    for (int i = 0; i < list.size(); i++)
        result[i] = new InternetAddress(list.get(i));
    return result;
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlText() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Simple html Email test");
    String html = loadHtml();// w ww. jav  a  2  s  .  c  om
    mail.setText(html, "UTF-8", "html");
    mail.setSentDate(new Date());
    Date sentDate = new Date(mail.getSentDate().getTime());
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Simple html Email test", message.getTitle());
    assertEquals(html, message.getBody());
    assertNotNull(message.getSentDate());
    assertEquals(sentDate.getTime(), message.getSentDate().getTime());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(0, message.getAttachmentsSize());
    assertEquals(0, message.getAttachments().size());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html; charset=UTF-8", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:com.alkacon.opencms.newsletter.CmsNewsletterSubscriptionBean.java

/**
 * Performs the send last newsletter to subscriber action and returns the text output for the result page.<p>
 * /*from  w  ww .  j  a va2s .  c o  m*/
 * @return the text output for the result page, according to the success of the send last newsletter to subscriber action
 */
public String actionSendLastNewsletter() {

    String result = getConfigText(XPATH_2_SENDLAST + NODE_ERROR);
    try {
        // get the newsletter file from the found ID
        CmsUUID fileId = getNewsletterManager().getSentNewsletterInfo(getConfigText(NODE_MAILINGLIST));
        if (fileId != null) {
            // found last sent newsletter ID, try to send the newsletter
            CmsResource res = getCmsObject().readResource(fileId);
            String fileName = getRequestContext().getSitePath(res);
            if (CmsStringUtil.isNotEmpty(fileName)) {
                // generate the newsletter mail and list of recipients (with the subscriber email)
                List<InternetAddress> recipients = new ArrayList<InternetAddress>(1);
                recipients.add(new InternetAddress(getEmail()));
                I_CmsNewsletterMailData mailData = CmsNewsletterManager.getMailData(this, recipients, fileName);
                String rootPath = res.getRootPath();
                if (mailData.getContent() != null) {
                    rootPath = mailData.getContent().getFile().getRootPath();
                }
                if (mailData.isSendable()) {
                    // send the email to the new subscriber
                    CmsNewsletterMail nlMail = new CmsNewsletterMail(mailData, mailData.getRecipients(), null,
                            rootPath);
                    nlMail.start();
                }
                result = getConfigText(XPATH_2_SENDLAST + NODE_OK);
            }
        }
    } catch (Exception e) {
        // sending last newsletter failed, show error
    }
    return result;
}

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);/*from  w  w  w .j  a  v  a2 s .  co  m*/

    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));
}