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.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from  w  w w  .  j a v a  2 s .  c  o  m
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public void addTo(final EmailAddress to) {
    try {/*www  . j av a  2s.  co  m*/
        if (to.hasName()) {
            source.addRecipient(RecipientType.TO, new InternetAddress(to.getEmail(), to.getName()));
        } else {
            source.addRecipient(RecipientType.TO, new InternetAddress(to.getEmail()));
        }
    } catch (final Exception e) {
        throw new GmailException("Failed adding To recipient", e);
    }
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXSendSMSFalse() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);//ww w  .ja  v  a  2  s.co m

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", false);

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSFalse.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertFalse(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

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

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!//from  w w w  . j  av a2  s .com
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        String mid = getId();

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        } else {
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.saveSentMessage(mid, mime, user);

        Thread thread = new Thread(new SendMessageThread(email));
        thread.start();
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

private EmailService makeALocalMailer() throws Exception {
    EmailService service = new EmailService();
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("localhost");
    sender.setPort(2525);//from w  w w  .  j  a  v a2  s  . c  o m
    ReflectionTestUtils.setField(service, "mailSender", sender);
    ReflectionTestUtils.setField(service, "senderAddress",
            new InternetAddress("admin@domain.com", "Domain Admin"));
    return service;
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 * ? E-mail ?./*  ww  w.ja v  a 2 s  . c  o  m*/
 *
 * @param request    ?  web-
 * @param exception ?
 * @return , ? ??? ? ?
 */
private String sendEmailToAdmin(HttpServletRequest request, Exception exception) {
    InternetAddress mail;
    String adminEmailAddress = configuration.getAdminEmailAddress();

    try {
        mail = new InternetAddress(adminEmailAddress, true);
    } catch (AddressException e) {
        return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress;
    }
    StringBuilder text = new StringBuilder();

    if (exception.getMessage() == null) {
        text.append(exception.getClass().getName());
    } else {
        text.append(exception.getMessage());
    }
    text.append("\n\n");

    Template tmpl = Template.getTemplate(request);
    //    text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri"));
    String mainUrl = "<unknown>";

    mainUrl = configuration.getMainUrl();

    text.append("Main URL: ").append(mainUrl).append(request.getServletPath());

    if (request.getQueryString() != null) {
        text.append('?').append(request.getQueryString()).append('\n');
    }
    text.append('\n');

    text.append("IP: " + request.getRemoteAddr() + '\n');

    text.append(" Headers: ");
    Enumeration enu = request.getHeaderNames();
    while (enu.hasMoreElements()) {
        String paramName = (String) enu.nextElement();
        text.append("\n         ").append(paramName).append(": ").append(request.getHeader(paramName));
    }
    text.append("\n\n");

    StringWriter exceptionStackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(exceptionStackTrace));
    text.append(exceptionStackTrace.toString());

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    try {
        emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));
        emailMessage.addRecipient(Message.RecipientType.TO, mail);
        emailMessage.setSubject("Linux.org.ru: " + exception.getClass());
        emailMessage.setSentDate(new Date());
        emailMessage.setText(text.toString(), "UTF-8");
    } catch (Exception e) {
        logger.error("An error occured while creating e-mail!", e);
        return EMAIL_NOT_SENT;
    }
    try {
        Transport.send(emailMessage);
        return EMAIL_SENT;
    } catch (Exception e) {
        return EMAIL_NOT_SENT;
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void trialCreated(String subject, String fromUser, String fromName, String toUser,
        InternetAddress[] toCC) {//from  www. j av a2  s .c  o  m
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link", "http://www.uengine.io/my/license");

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/trial-created.vm", "UTF-8",
            model);

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

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

/**
 * DOCUMENT ME!/*from  w  w w. j av  a2s .  c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param msession DOCUMENT ME!
 * @param userObj DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 * @throws MailException DOCUMENT ME!
 */
public void register(org.hibernate.Session hsession, Session msession, UserObj userObj,
        String defaultEmailDomain) throws Exception {
    try {
        Users users = new Users();
        users.setUseActive(false);
        users.setUseEmail(userObj.getEmail());
        users.setUseLanguage(userObj.getLanguage());
        users.setUseName(userObj.getName());
        users.setUsePassword(userObj.getPassword());
        users.setUseRegisterDate(new Date());
        users.setUseUsername(userObj.getUsername());

        hsession.save(users);
        hsession.flush();

        MailPreferences mailPreferences = new MailPreferences();
        mailPreferences.setUsers(users);
        mailPreferences.setMaprHtmlMessage(true);
        mailPreferences.setMaprMessagesByPage(20);
        mailPreferences.setMaprQuotaSize(0);
        mailPreferences.setMaprSignature("--\n" + userObj.getName());
        mailPreferences.setMaprSpamTolerance(100);
        mailPreferences.setMaprVacationActive(false);

        hsession.save(mailPreferences);
        hsession.flush();

        Identity identity = new Identity();
        identity.setIdeActive(true);
        identity.setIdeCode(RandomStringUtils.randomAlphanumeric(25));
        identity.setIdeDefault(true);
        identity.setIdeEmail(userObj.getUsername() + "@" + defaultEmailDomain);
        identity.setIdeName(userObj.getName());
        identity.setIdeReplyTo(userObj.getUsername() + "@" + defaultEmailDomain);
        identity.setUsers(users);

        hsession.save(identity);
        hsession.flush();

        InternetAddress from = new InternetAddress(userObj.getEmail(), userObj.getName());

        Criteria crit = hsession.createCriteria(Roles.class);
        crit.add(Restrictions.eq("rolName", "admin"));

        Roles role = (Roles) crit.uniqueResult();

        InternetAddress[] to = new InternetAddress[role.getUserRoles().size()];
        Iterator it = role.getUserRoles().iterator();
        int i = 0;

        while (it.hasNext()) {
            UserRole userRole = (UserRole) it.next();
            Users aux = userRole.getId().getUsers();
            Criteria criteria = hsession.createCriteria(Identity.class);
            criteria.add(Restrictions.eq("ideDefault", new Boolean(true)));
            criteria.add(Restrictions.eq("ideActive", new Boolean(true)));
            criteria.add(Restrictions.eq("users", aux));

            Identity id = (Identity) criteria.uniqueResult();

            to[i] = new InternetAddress(id.getIdeEmail(), id.getIdeName());
            i++;
        }

        notifyToAdmins(msession, from, to, userObj.getUsername() + " (" + userObj.getName() + ")");
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

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

License:asdf

@Test
public void addInvitation_sendInvitation_properConfiguration()
        throws MessagingException, UnsupportedEncodingException {
    MockitoAnnotations.initMocks(this);
    when(detailsFinder.findUserName(any(Authentication.class))).thenReturn(USER);
    when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
    setUpNotExistingUserRequest(INVITATION_MAIL);
    when(accessInvitationsService.getAccessInvitations(INVITATION_MAIL)).thenReturn(Optional.empty());
    when(invitationLinkGenerator.getLink(anyString())).thenReturn("http://example.com");

    InvitationModel invitation = InvitationModel.of(INVITATION_MAIL, false);

    ResponseEntity<String> response = postForEntityWithToken(restTemplate, TOKEN, baseUrl + "rest/invitations",
            invitation, String.class);

    assertEquals(response.getStatusCode(), HttpStatus.OK);

    verify(mailSender).send(any(MimeMessage.class));
    verify(mimeMessage).addRecipients(any(Message.RecipientType.class), eq(INVITATION_MAIL));
    verify(mimeMessage).addFrom((Address[]) addressCaptor.capture());
    Address[] addresses = (Address[]) addressCaptor.getValue();
    assertEquals(new InternetAddress(SUPPORT_EMAIL, EMAIL_NAME), addresses[0]);
}

From source file:com.duroty.application.chat.manager.ChatManager.java

/**
 * DOCUMENT ME!/* w  w w  .j a v a 2s .c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param userSender DOCUMENT ME!
 * @param userRecipient DOCUMENT ME!
 */
private void sendMail(Session hsession, javax.mail.Session msession, Users userSender, Users userRecipient,
        String message) {
    try {
        String sender = userSender.getUseUsername();
        String recipient = userRecipient.getUseUsername();

        Identity identitySender = getIdentity(hsession, userSender);
        Identity identityRecipient = getIdentity(hsession, userRecipient);

        HtmlEmail email = new HtmlEmail();
        InternetAddress _from = new InternetAddress(identitySender.getIdeEmail(), identitySender.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identitySender.getIdeReplyTo(),
                identitySender.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(identityRecipient.getIdeEmail(), null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _from);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        email.setCharset(charset);
        email.setSubject("Chat " + sender + " >> " + recipient);
        email.setHtmlMsg(message);

        calendar.setTime(new Date());

        String minute = "30";

        if (calendar.get(Calendar.MINUTE) >= 30) {
            minute = "60";
        }

        String value = String.valueOf(calendar.get(Calendar.YEAR))
                + String.valueOf(calendar.get(Calendar.MONTH)) + String.valueOf(calendar.get(Calendar.DATE))
                + String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)) + minute
                + String.valueOf(userSender.getUseIdint() + userRecipient.getUseIdint());
        String reference = "<" + value + ".JavaMail.duroty@duroty" + ">";
        email.addHeader(RFC2822Headers.IN_REPLY_TO, reference);
        email.addHeader(RFC2822Headers.REFERENCES, reference);

        email.addHeader("X-DBox", "CHAT");

        Date now = new Date();
        email.setSentDate(now);

        email.setMailSession(msession);
        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (controlQuota(hsession, userSender, size)) {
            //messageable.saveSentMessage(null, mime, userSender);
            Thread thread = new Thread(new SendMessageThread(email));
            thread.start();
        }
    } catch (UnsupportedEncodingException e) {
    } catch (MessagingException e) {
    } catch (EmailException e) {
    } catch (Exception e) {
    }
}