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:com.rodaxsoft.mailgun.ListMember.java

/**
 * Sets the email address// w  ww .  ja  v a2s  .c o m
 * @param address The email address to set
 * @throws ContextedRuntimeException if the email address format is invalid
 */
public void setAddress(String address) {

    try {
        new InternetAddress(address, true);
    } catch (AddressException e) {
        throw new ContextedRuntimeException(e).addContextValue("address", address).addContextValue("position",
                e.getPos());
    }

    this.address = address;
}

From source file:ee.cyber.licensing.service.MailService.java

public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId)
        throws MessagingException, IOException, SQLException {
    License license = licenseRepository.findById(licenseId);
    List<Contact> contacts = contactRepository.findAll(license.getCustomer());
    List<String> receivers = getReceivers(mailbody, contacts);

    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//  ww w .  j  ava  2  s  .  c  om
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "License dude"));
    //mailMessage.setReplyTo(InternetAddress.parse(email, false));
    mailMessage.setSubject(mailbody.getSubject());
    //String emailBody = body + "<br><br> Regards, <br>Cybernetica team";
    mailMessage.setSentDate(new Date());

    for (String receiver : receivers) {
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
    }

    if (fileId != 0) {
        MailAttachment file = fileRepository.findById(fileId);
        if (file != null) {
            String fileName = file.getFileName();
            byte[] fileData = file.getData_b();
            if (fileName != null) {
                // Create a multipart message for attachment
                Multipart multipart = new MimeMultipart();
                // Body part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailbody.getBody(), "text/html");
                multipart.addBodyPart(messageBodyPart);

                //Attachment part
                messageBodyPart = new MimeBodyPart();
                ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                mailMessage.setContent(multipart);
            }
        }
    } else {
        mailMessage.setContent(mailbody.getBody(), "text/html");
    }

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void addRecipientsWhitelist(MimeMessage message, String to_address, String to_name,
        GreetingcardConfig greetingcardConfig) throws UnsupportedEncodingException, MessagingException {
    WhitelistDao whitelistDao = new JdbcWhitelistDao(greetingcardConfig);
    List<String> receivers = new ArrayList<String>();

    if ((to_address != null) && to_address.contains("@"))
        receivers.add(to_address);//from w  ww.  ja v  a 2  s  .c o m
    else
        try {
            receivers = whitelistDao.getReceiverlist(to_name);
        } catch (DataAccessException e) {
        }

    Iterator<String> itr = receivers.iterator();
    String receiverAddress;
    String receiverName = null;
    while (itr.hasNext()) {
        receiverAddress = itr.next();
        try {
            receiverName = whitelistDao.getReceiverName(receiverAddress);
        } catch (DataAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiverAddress, receiverName));
    }
}

From source file:nu.yona.server.email.EmailService.java

public void prepareMimeMessage(MimeMessage mimeMessage, String senderName, InternetAddress receiverAddress,
        String subjectTemplateName, String bodyTemplateName, Map<String, Object> templateParameters)
        throws MessagingException, UnsupportedEncodingException {
    Context ctx = ThymeleafUtil.createContext();
    ctx.setVariable("includedMediaBaseUrl", yonaProperties.getEmail().getIncludedMediaBaseUrl());
    ctx.setVariable("appleAppStoreUrl", yonaProperties.getEmail().getAppleAppStoreUrl());
    ctx.setVariable("googlePlayStoreUrl", yonaProperties.getEmail().getGooglePlayStoreUrl());
    templateParameters.entrySet().stream().forEach(e -> ctx.setVariable(e.getKey(), e.getValue()));

    String subjectText = emailTemplateEngine.process(subjectTemplateName + ".txt", ctx);
    String bodyText = emailTemplateEngine.process(bodyTemplateName + ".html", ctx);

    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
    message.setFrom(new InternetAddress(yonaProperties.getEmail().getSenderAddress(), senderName));
    message.setTo(receiverAddress);/*from   ww  w.j  a v  a  2 s  .c o  m*/
    message.setSubject(subjectText);
    message.setText(bodyText, true);
}

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessageTest.java

public static Email getSimpleMail(InternetAddress from) throws UnsupportedEncodingException {
    return EmailImpl.builder().from(from)
            .replyTo(new InternetAddress("tullius.cicero@urbs.aeterna", "Marcus Tullius Cicero"))
            .to(Lists.newArrayList(new InternetAddress("titus@de-rerum.natura", "Pomponius Attcus")))
            .cc(Lists.newArrayList(new InternetAddress("tito55@de-rerum.natura", "Titus Lucretius Carus"),
                    new InternetAddress("info@de-rerum.natura", "Info Best Seller")))
            .bcc(Lists.newArrayList(new InternetAddress("caius-memmius@urbs.aeterna", "Caius Memmius")))
            .subject("Laelius de amicitia")
            .body("Firmamentum autem stabilitatis constantiaeque eius, quam in amicitia quaerimus, fides est.")
            .encoding(Charset.forName("UTF-8")).build();
}

From source file:com.miserablemind.butter.domain.service.email.EmailManager.java

/**
 * Sends e-mail to user when user requests a password reset.
 *
 * @param appUser            user instance an e-mail message is being sent to
 * @param passwordResetToken a token that is used for building URL that user clicks on to reset password.
 * @param configApp          app specific configuration in order to retrieve "from" value and base url
 * @throws UnsupportedEncodingException/*from w  ww  . jav  a2  s .  c o  m*/
 */
@Async
public void sendEmailResetPassword(AppUser appUser, String passwordResetToken, ConfigApp configApp)
        throws UnsupportedEncodingException {
    String subjectLine = "Password Reset - " + configApp.getAppName();

    InternetAddress fromField = new InternetAddress(configApp.getEmailAddressNoReply(),
            configApp.getAppName() + " - No Reply");

    EmailMessage emailMessage = new EmailMessage(appUser.getEmail(), fromField, subjectLine, null,
            "password-reset.vm");
    emailMessage.addModelProperty("userName", appUser.getUsername());
    emailMessage.addModelProperty("appName", configApp.getAppName());
    emailMessage.addModelProperty("resetUrl", configApp.getBaseAppUrl() + "/reset-password/?token="
            + passwordResetToken + "&amp;email=" + URLEncoder.encode(appUser.getEmail(), "UTF-8"));

    this.emailService.sendMimeMail(emailMessage);

}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {/*from  ww w .ja  va2 s.c  om*/
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

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

public void sendMail(String host, String from, String to, String subject, String messageText) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);

    try {//from ww w .  java 2  s  .  c o  m
        MimeMessage msg = new MimeMessage(session);
        String[] recipientStrings = to.split(",");
        InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
        try {
            msg.setFrom(new InternetAddress(from, charset));
            for (int i = 0; i < recipients.length; i++) {
                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(messageText, charset);
        Transport.send(msg, recipients);
    } catch (AddressException ae) {
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        me.printStackTrace(System.out);
    }
}

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

private MimeMessage getMessage(Address[] addressArray, String from, String content, String title)
        throws MessagingException {
    Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
    session.setDebug(false);//  w w w  .  j a v a  2  s.c o  m
    SMTPMessage msg = new SMTPMessage(session);
    if (StringUtils.isNotEmpty(from)) {
        InternetAddress ss;
        try {
            ss = new InternetAddress(m_bag.m_fromAddress.getAddress(),
                    MimeUtility.encodeText(from, "gb2312", "b"));
            msg.setFrom(ss);
        } catch (UnsupportedEncodingException e) {
            msg.setFrom(m_bag.m_fromAddress);
        }
        msg.setReplyTo(new InternetAddress[] { new InternetAddress(from) });
    } else {
        msg.setFrom(m_bag.m_fromAddress);
    }
    msg.setRecipients(Message.RecipientType.TO, addressArray);
    try {
        msg.setSubject(MimeUtility.encodeText(title, UTF_8, "B"));
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage(), e);
    }
    msg.setSentDate(new Date());
    msg.setContent(content, EMAIL_CONTENT_TYPE);
    return msg;
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();/* ww  w.java  2 s .c o m*/
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(mimeMessage, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}