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) throws UnsupportedEncodingException 

Source Link

Document

Construct an InternetAddress given the address and personal name.

Usage

From source file:org.trustedanalytics.user.invite.EmailServiceTest.java

@Test
public void sendMimeMessage_fromAddress() throws MessagingException, UnsupportedEncodingException {
    doReturn(mimeMessage).when(mailSender).createMimeMessage();
    sut.sendMimeMessage("", "", "");
    verify(mimeMessage).addFrom((Address[]) addressCaptor.capture());
    assertThat(addressCaptor.getValue(), arrayContaining(new InternetAddress(SUPPORT_EMAIL, PERSONAL_NAME)));
}

From source file:com.rodaxsoft.mailgun.ListMember.java

@Override
public String getType() {

    if (address != null) {
        try {/*from  w ww  . ja  v a  2 s.  c om*/
            return new InternetAddress(address, name).getType();
        } catch (UnsupportedEncodingException e) {
            throw new ContextedRuntimeException(e);
        }
    } else {
        return null;
    }
}

From source file:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {//from www .j  a va2s.  c  o m
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.mime.charset", "UTF-8");
        props.put("mail.smtp.ssl.enable", ssl);

        Session session = Session.getInstance(props, new EmailAuthenticator(username, password));

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, ""));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject(subject);
        message.setText(content, "utf-8", "html");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException | UnsupportedEncodingException ex) {
        log.error(
                "?  ? email,  : "
                        + ex.getLocalizedMessage());
        ex.printStackTrace();
    }

}

From source file:org.eel.kitchen.jsonschema.format.EmailFormatAttribute.java

@Override
public void checkValue(final String fmt, final ValidationContext ctx, final ValidationReport report,
        final JsonNode instance) {
    // Yup, that is kind of misnamed. But the problem is with the
    // InternetAddress constructor in the first place which "enforces" a
    // syntax which IS NOT strictly RFC compliant.
    final boolean strictRFC = ctx.hasFeature(ValidationFeature.STRICT_RFC_CONFORMANCE);

    try {/*from ww w  . ja  v  a2s.  c om*/
        // Which means we actually invert it.
        new InternetAddress(instance.textValue(), !strictRFC);
    } catch (AddressException ignored) {
        final Message.Builder msg = newMsg(fmt).setMessage("string is not a valid email address")
                .addInfo("value", instance);
        report.addMessage(msg.build());
    }
}

From source file:com.rodaxsoft.mailgun.ListMemberRequest.java

/**
 * Set the list member email address/*from w ww . ja  v  a  2  s.c  om*/
 * @param address The email address to set
 * @return ListMemberRequest object
 * @throws ContextedRuntimeException if the address format is invalid.
 * 
 */
public ListMemberRequest setAddress(String address) {
    try {
        new InternetAddress(address, true);
    } catch (AddressException e) {
        throw new ContextedRuntimeException(e).addContextValue("address", address).addContextValue("position",
                e.getPos());
    }

    parameters.put(ADDRESS_KEY, address);
    return this;
}

From source file:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody//from   w ww .j  a va  2  s .  com
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

From source file:dk.teachus.backend.bean.impl.MailMessageSendingBean.java

/**
 * Only allow one execution of this at a time
 *//*  ww  w.j  a va 2 s. c o m*/
public synchronized void sendMailMessages() {
    List<Message> unsentMessages = messageDAO.getUnsentMessages();

    for (Message message : unsentMessages) {
        if (message instanceof MailMessage) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Sending new message with id: " + message.getId() + " and subject: "
                            + message.getSubject());
                }

                MailMessage mailMessage = (MailMessage) message;

                Person recipientPerson = mailMessage.getRecipient();
                Person senderPerson = mailMessage.getSender();

                InternetAddress sender = new InternetAddress(senderPerson.getEmail(),
                        mailMessage.getSender().getName());
                InternetAddress recipient = new InternetAddress(recipientPerson.getEmail(),
                        recipientPerson.getName());
                String subject = mailMessage.getSubject();

                String body = mailMessage.getBody();
                body = body.replace("${recipient.name}", recipientPerson.getName());
                body = body.replace("${recipient.email}", recipientPerson.getEmail());
                body = body.replace("${sender.name}", senderPerson.getName());
                body = body.replace("${sender.email}", senderPerson.getEmail());

                if (log.isDebugEnabled()) {
                    log.debug("Sending mail to: " + recipient);
                }

                try {
                    mailBean.sendMail(sender, recipient, subject, body, mailMessage.getType());
                    message.setState(MessageState.SENT);

                    if (log.isDebugEnabled()) {
                        log.debug("Message succesfully sent: " + message.getId());
                    }
                } catch (RecipientErrorMailException e) {
                    message.setState(MessageState.ERROR_SENDING_INVALID_RECIPIENT);

                    log.warn("Couldn't send the message because of an invalid recipient", e);
                } catch (MailException e) {
                    message.setState(MessageState.ERROR_SENDING_UNKNOWN);

                    log.warn("Message couln't be send due to unknown error", e);
                }

                message.setProcessingDate(new DateTime());
                messageDAO.save(message);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }//  w  w w .j  a va2  s  .  c  o m

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}

From source file:com.duroty.application.open.manager.OpenManager.java

/**
 * DOCUMENT ME!// ww  w .  j  av  a2 s .  c  om
 *
 * @param hsession DOCUMENT ME!
 * @param msession DOCUMENT ME!
 * @param data DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public void forgotPassword(org.hibernate.Session hsession, Session msession, String data) throws Exception {
    try {
        int pos = data.indexOf('@');

        if (pos > -1) {
            data = data.substring(0, pos);
        }

        Criteria criteria = hsession.createCriteria(Users.class);
        criteria.add(Restrictions.eq("useUsername", data));

        Users user = (Users) criteria.uniqueResult();

        if (user != null) {
            InternetAddress _to = new InternetAddress(user.getUseEmail(), user.getUseName());

            Criteria crit = hsession.createCriteria(Identity.class);
            crit.add(Restrictions.eq("users", user));
            crit.add(Restrictions.eq("ideActive", new Boolean(true)));
            crit.add(Restrictions.eq("ideDefault", new Boolean(true)));

            Identity identity = (Identity) crit.uniqueResult();
            InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

            Iterator it = user.getMailPreferenceses().iterator();
            MailPreferences mailPreferences = (MailPreferences) it.next();

            sendData(msession, _from, _to, user.getUseUsername(), user.getUsePassword(),
                    mailPreferences.getMaprSignature());
        }
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param emailAddress/*w  w  w  .  j a  v a 2s  .  c o m*/
 * @param displayName
 * @return
 */
public static String toInternetAddress(String emailAddress, String displayName) {

    InternetAddress address;
    try {
        if (!StringUtils.isEmpty(displayName)) {
            address = new InternetAddress(emailAddress, displayName);
            return address.toUnicodeString();
        } else {
            return emailAddress;
        }
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}