Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

/**
 * Store general propreties (mailJet), create session and addressFrom
 *
 * @param mapConfigEmail//  www. j a  va 2  s  . c  om
 * @return
 * @throws AddressException
 * @throws MessagingException
 */
private Map<String, Object> initEmailConfig(Map<String, Object> mapConfigEmail)
        throws AddressException, MessagingException {

    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(this.getClass(), "/fr.treeptik.cloudunit.templates/");

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.socketFactory.port", socketFactoryPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", smtpPort);

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(apiKey, secretKey);
        }
    });

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(emailFrom));

    mapConfigEmail.put("message", message);
    mapConfigEmail.put("configuration", configuration);

    return mapConfigEmail;

}

From source file:it.infn.ct.security.actions.ActivateAccount.java

private void sendMail(LDAPUser user, boolean enabled) throws MailException {
    javax.mail.Session session = null;//from  w w w. j  av  a 2  s .co  m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(user.getPreferredMail());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        _log.error("mail bcc: " + mailBCC);
        String ccMail[] = mailBCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.BCC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");
        if (enabled) {
            mailBody = mailBody.replace("_RESULT_", "accepted");
        } else {
            mailBody = mailBody.replace("_RESULT_", "denied");
        }
        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:com.gitlab.anlar.lunatic.server.ServerTest.java

private Message createBaseMessage(String from, String to, String subject, Session session)
        throws MessagingException {
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(to) });
    msg.setSentDate(new Date());
    msg.setSubject(subject);/*from  w w  w . j a v a2  s. co m*/

    return msg;
}

From source file:it.infn.ct.security.actions.ExtendAccount.java

private void sendMail() throws MailException {
    javax.mail.Session session = null;/*from w  ww .  j a va  2s .c om*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:mitm.application.djigzo.james.mailets.Attach.java

@Override
public void serviceMail(Mail mail) {
    try {//w  ww  .j a  v a 2s.  c  o  m
        MimeMessage sourceMessage = mail.getMessage();

        MimeMessage newMessage = retainMessageID
                ? new MimeMessageWithID(MailSession.getDefaultSession(), sourceMessage.getMessageID())
                : new MimeMessage(MailSession.getDefaultSession());

        if (StringUtils.isNotEmpty(filename)) {
            newMessage.setFileName(filename);
        }

        Multipart mp = new MimeMultipart();

        HeaderMatcher contentMatcher = new ContentHeaderNameMatcher();

        mp.addBodyPart(BodyPartUtils.makeContentBodyPart(sourceMessage, contentMatcher));

        newMessage.setContent(mp);

        /* 
         * create a matcher that matches on everything expect content-* 
         */
        HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(contentMatcher);

        /* 
         * copy all non-content headers from source message to the new message 
         */
        HeaderUtils.copyHeaders(sourceMessage, newMessage, nonContentMatcher);

        newMessage.saveChanges();

        mail.setMessage(newMessage);
    } catch (MessagingException e) {
        getLogger().error("Error attaching the message.", e);
    } catch (IOException e) {
        getLogger().error("Error attaching the message.", e);
    }
}

From source file:net.sourceforge.subsonic.backend.service.EmailSession.java

private MimeMessage createMessage(String from, List<String> to, List<String> cc, List<String> bcc,
        List<String> replyTo, String subject) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));
    message.setReplyTo(new Address[] { new InternetAddress(from) });
    message.setRecipients(Message.RecipientType.TO, convertAddress(to));
    message.setRecipients(Message.RecipientType.CC, convertAddress(cc));
    message.setRecipients(Message.RecipientType.BCC, convertAddress(bcc));
    message.setReplyTo(convertAddress(replyTo));
    message.setSubject(subject);/*from w  w w  . ja va2 s . c om*/
    return message;
}

From source file:de.micromata.genome.gwiki.model.GWikiStandardEmailProvider.java

public void sendEmailImpl(Map<String, String> ctx) throws MessagingException {
    Map<String, String> headers = new HashMap<String, String>();
    if (ctx.containsKey(TO) == true) {
        headers.put(TO, ctx.get(TO));/*from w  w w  .ja v  a  2s . c  o  m*/
    }
    if (ctx.containsKey(FROM) == true) {
        headers.put(FROM, ctx.get(FROM));
    }
    if (ctx.containsKey(CC) == true) {
        headers.put(CC, ctx.get(CC));
    }
    if (ctx.containsKey(BCC) == true) {
        headers.put(BCC, ctx.get(BCC));
    }
    if (ctx.containsKey(SUBJECT) == true) {
        headers.put(SUBJECT, ctx.get(SUBJECT));
    }
    Session emailSession = getEmailSession();
    if (emailSession == null) {
        GWikiLog.warn("Cannot send email, because no emailSession is configured");
        return;
    }
    MimeMessage message = new MimeMessage(emailSession);
    String encoding = DEFAULT_MAIL_ENCODING;
    GWikiMailHelper mh = new GWikiMailHelper(message, false, encoding);
    setHeaders(mh, headers);
    mh.setBody(ctx.get(TEXT));
    Transport.send(message);
}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /* w ww. ja v a 2 s  . com*/
 * @param fromAddress
 * @param ccRe
 * @param toRecipient
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @return status message
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient,
        final String subject, final String body, final String messageType) throws IllegalArgumentException {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipient == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;

    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) toRecipient;
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address toAddress = new InternetAddress(toRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException {
    InternetAddress[] to = createAddresses(mailMessage.getToArray());
    InternetAddress[] cc = createAddresses(mailMessage.getCcArray());
    InternetAddress[] bcc = createAddresses(mailMessage.getBccArray());
    if (to.length == 0) {
        to = InternetAddress.parse(defaultTo);
    }/*w  w  w  .  j  a v a 2s  .co m*/

    String subject = mailMessage.getSubject();
    if (subjectPrefix != null && !subjectPrefix.equals("")) {
        subject = subjectPrefix + " " + subject;
    }

    MimeMultipart content = new MimeMultipart("related");

    //Create attachments
    DataSource[] attachments = mailMessage.getAttachmentsArray();
    for (int i = 0; i < attachments.length; i++) {
        DataSource attachment = attachments[i];
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);
        content.addBodyPart(attachmentPart);
    }

    //Create message body
    MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml());
    content.addBodyPart(bodyPart);

    MimeMessage message = new MimeMessage(session);
    if (from == null) {
        message.setFrom(); //Uses mail.from property
    } else {
        message.setFrom(new InternetAddress(from));
    }
    message.setRecipients(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.CC, cc);
    message.setRecipients(Message.RecipientType.BCC, bcc);
    message.setSubject(subject);
    message.setContent(content);
    return message;
}

From source file:com.ayu.filter.RegularService.java

@Async
public void sendSSLMail(String text, String toMail) {

    final String username = "clouddefenceids";
    final String password = "";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from www.j a v  a  2  s  . c  o  m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
        message.setSubject("Forgot Password");
        message.setText(text);

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}