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, String personal, String charset) throws UnsupportedEncodingException 

Source Link

Document

Construct an InternetAddress given the address and personal name.

Usage

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {/*from   w w w  . j ava2  s  .c o  m*/
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:ru.mystamps.web.service.MailServiceImpl.java

@SuppressWarnings("PMD.UseObjectForClearerAPI")
private void sendMail(final String email, final String subject, final String text, final String tag) {

    try {//w w w  . j a va 2 s . c  o m
        // We're using MimeMessagePreparator only because of its capability of adding headers.
        // Otherwise we would use SimpleMailMessage class.
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            @SuppressWarnings("PMD.SignatureDeclareThrowsException")
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
                message.setValidateAddresses(true);
                message.setTo(email);
                message.setFrom(new InternetAddress(robotEmail, "My Stamps", "UTF-8"));
                message.setSubject(subject);
                message.setText(text);

                // see: http://documentation.mailgun.com/user_manual.html#sending-via-smtp
                message.getMimeMessage().addHeader("X-Mailgun-Tag", tag);
                if (testMode) {
                    message.getMimeMessage().addHeader("X-Mailgun-Drop-Message", "yes");
                }
            }
        };

        mailer.send(preparator);

    } catch (MailException ex) {
        throw new EmailSendingException("Can't send mail to e-mail " + email, ex);
    }
}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);/*from w  w w . java2s  .  c  om*/
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

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

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:org.obm.imap.archive.services.MailerImpl.java

@VisibleForTesting
Address from(ObmDomain domain) {/*from  ww  w.  j a  v a 2 s  . c  o  m*/
    try {
        return new InternetAddress(EMAIL_FROM + EMAIL_AT + domain.getName(), EMAIL_FROM_DISPlAY_NAME,
                Charsets.UTF_8.name());
    } catch (Exception e) {
        logger.error("Cannot build From address", e);
        return null;
    }
}

From source file:com.github.aynu.mosir.core.enterprise.mail.MailServiceImpl.java

/** {@inheritDoc} */
@Override/*from   ww  w.ja  v  a  2 s  .c o  m*/
public InternetAddress createAddress(final String address, final String personal)
        throws UnsupportedEncodingException {
    return new InternetAddress(address, personal, ConfigHelper.INET_ADDRESS_CHARSET);
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

private ValueBag readProperties() {
    ValueBag bag = new ValueBag();
    bag.m_mailProperties = new Properties();
    bag.m_mailProperties.put("mail.smtp.host", systemProperty.getProperty("email.mail.smtp.host"));
    bag.m_mailProperties.put("mail.smtp.auth", systemProperty.getProperty("email.mail.smtp.auth"));
    bag.m_mailProperties.put("mail.pop3.host", systemProperty.getProperty("email.mail.pop3.host"));
    String userId = systemProperty.getProperty(PROP_EMAIL_USERID);
    String password = systemProperty.getProperty(PROP_EMAIL_PASSWORD);
    bag.m_authenticator = new EmailAuthenticator(userId, password);
    String mailFrom = systemProperty.getProperty(PROP_EMAIL_FROMADDRESS);
    try {//from  www. j a  va 2  s.  com
        bag.m_fromAddress = new InternetAddress(mailFrom, EMAIL_DISPLAY_NAME, UTF_8);
    } catch (UnsupportedEncodingException e) {
        LOG.error("", e);
    }
    return bag;
}

From source file:com.kuzumeji.framework.enterprise.component.mail.MailServiceImpl.java

/** {@inheritDoc} */
@Override/*from w  w w. j av  a  2  s. com*/
public InternetAddress createAddress(final String address, final String personal)
        throws UnsupportedEncodingException {
    return new InternetAddress(address, personal, INET_ADDRESS_CHARSET);
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public boolean sendSystemEmail(String to, String subject, String messageText) {

    boolean sent = false;
    String rootDataverseName = dataverseService.findRootDataverse().getName();
    String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing",
            Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName)));
    logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body);
    try {//from   w  w w .ja  v  a 2s .  com
        MimeMessage msg = new MimeMessage(session);
        InternetAddress systemAddress = getSystemAddress();
        if (systemAddress != null) {
            msg.setFrom(systemAddress);
            msg.setSentDate(new Date());
            String[] recipientStrings = to.split(",");
            InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
            for (int i = 0; i < recipients.length; i++) {
                try {
                    recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset);
                } catch (UnsupportedEncodingException ex) {
                    logger.severe(ex.getMessage());
                }
            }
            msg.setRecipients(Message.RecipientType.TO, recipients);
            msg.setSubject(subject, charset);
            msg.setText(body, charset);
            try {
                Transport.send(msg, recipients);
                sent = true;
            } catch (SMTPSendFailedException ssfe) {
                logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)");
            }
        } else {
            logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set ("
                    + Key.SystemEmail + " setting).");
        }
    } catch (AddressException ae) {
        logger.warning("Failed to send mail to " + to);
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        logger.warning("Failed to send mail to " + to);
        me.printStackTrace(System.out);
    }
    return sent;
}

From source file:de.blizzy.documentr.mail.SubscriptionMailer.java

private Address createAddress(String email, String name) {
    try {/*from   w  w w  .j a  v a  2 s  .  c  o  m*/
        return new InternetAddress(email, name, Charsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

public AbstractMailClient setFrom(String address, String personal) throws AddressException {
    try {/* w  w  w. ja v a2s.c  om*/
        return setFrom(new InternetAddress(address, personal, CharsetUtils.UTF_8.displayName()));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 not supported?", e);
    }
}