Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

/**
 * Build a {@link MimeMessage} instance from the set of supplied parameters.
 * @return The {@link MimeMessage} instance;
 * @throws MessagingException/* w ww .ja v  a  2s . c  om*/
 * @throws UnsupportedEncodingException
 */
public MimeMessage buildMimeMessage() throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());

    setJenkinsInstanceIdent(msg);

    msg.setContent("", contentType());
    if (StringUtils.isNotBlank(from)) {
        msg.setFrom(toNormalizedAddress(from));
    }
    msg.setSentDate(new Date());

    addSubject(msg);
    addBody(msg);
    addRecipients(msg);

    if (!replyTo.isEmpty()) {
        msg.setReplyTo(toAddressArray(replyTo));
    }
    return msg;
}

From source file:controllerClasses.security.SiteuserControl.java

private void sendMail(String email, String subject, String body)
        throws NamingException, javax.mail.MessagingException {

    javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(mailAOSMail);
    message.setSubject(subject);//  w w  w  .ja v a  2 s .c o m
    message.setRecipients(javax.mail.Message.RecipientType.TO,
            javax.mail.internet.InternetAddress.parse(email, false));
    message.setContent(body, "text/html");
    javax.mail.Transport.send(message);
}

From source file:mailhost.StartApp.java

public void sendEmail(String to, String subject, String body)
        throws UnsupportedEncodingException, MessagingException {

    System.out.println(String.format("Sending notification email recipients " + "to  " + to + " subject  "
            + subject + "host " + mailhost));

    if (StringUtils.isBlank(to))
        throw new IllegalArgumentException("The email request should have at least one recipient");

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", mailhost);

    Session session = Session.getDefaultInstance(properties);
    Address[] a = new InternetAddress[1];
    a[0] = new InternetAddress("test@matson.com");

    MimeMessage message = new MimeMessage(session);

    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.addFrom(a);//from w w w.  java2  s  . c  o m

    message.setSubject(subject);
    message.setContent(body, "text/html; charset=utf-8");
    //message.setText(body);

    // Send message
    Transport.send(message);
    System.out.println("Email sent.");
}

From source file:org.quartz.jobs.ee.mail.SendMailJob.java

protected void setMimeMessageContent(MimeMessage mimeMessage, MailInfo mailInfo) throws MessagingException {
    if (mailInfo.getContentType() == null) {
        mimeMessage.setText(mailInfo.getMessage());
    } else {// w w  w.j  a va2 s  .co m
        mimeMessage.setContent(mailInfo.getMessage(), mailInfo.getContentType());
    }
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testValidateMessageShouldFail() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();/*from  w  w w. ja va2  s  . c  o m*/

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}

From source file:org.b3log.solo.mail.local.MailSender.java

/**
 * Converts the specified message into a {@link javax.mail.Message
 * javax.mail.Message}.//from  w w  w . j  a  va 2 s  .  c o  m
 *
 * @param message the specified message
 * @return a {@link javax.mail.internet.MimeMessage}
 * @throws Exception if converts error
 */
public javax.mail.Message convert2JavaMailMsg(final Message message) throws Exception {
    if (null == message) {
        return null;
    }

    if (StringUtils.isBlank(message.getFrom())) {
        throw new MessagingException("Null from");
    }

    if (null == message.getRecipients() || message.getRecipients().isEmpty()) {
        throw new MessagingException("Null recipients");
    }

    final MimeMessage ret = new MimeMessage(getSession());

    ret.setFrom(new InternetAddress(message.getFrom()));
    final String subject = message.getSubject();

    ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B"));
    final String htmlBody = message.getHtmlBody();

    ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8");
    ret.addRecipients(RecipientType.TO, transformRecipients(message.getRecipients()));

    return ret;
}

From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java

/**
 * Creates empty mail.//ww  w  .j a v a2s. c  om
 *
 * @param build build.
 * @param listener listener.
 * @return empty mail.
 * @throws MessagingException exception if any.
 */
protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(getRecipients());
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address
            try {
                rcp.add(new InternetAddress(address));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    if (CollectionUtils.isNotEmpty(upstreamProjects)) {
        for (AbstractProject project : upstreamProjects) {
            includeCulpritsOf(project, build, listener, rcp);
        }
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:org.codice.ddf.catalog.ui.query.FeedbackApplication.java

@Override
public void init() {
    post("/feedback", APPLICATION_JSON, (req, res) -> {
        if (StringUtils.isNotEmpty(emailDestination)) {
            FeedbackRequest feedback = parseFeedbackRequest(util.safeGetBody(req));
            feedback.setAuthUsername(getCurrentUser());

            String emailSubject = getEmailSubject(feedback);
            String emailBody = getEmailBody(feedback);
            if (emailBody != null) {
                emailBody = emailBody.replaceAll("\\\\n", "\n");
            } else {
                emailBody = "<html/>";
            }/*w ww.ja v  a2  s  .  co  m*/

            Session emailSession = smtpClient.createSession();
            MimeMessage message = new MimeMessage(emailSession);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailDestination));
            message.setSubject(emailSubject);
            message.setContent(emailBody, "text/html; charset=utf-8");
            smtpClient.send(message);

            res.body("{}");
            res.status(200);
            return res;
        } else {
            res.status(500);
            res.body("No destination email configured, feedback cannot be submitted.");
            LOGGER.debug("Feedback submission failed, destination email is not configured.");
            return res;
        }
    });

    exception(Exception.class, (e, request, response) -> {
        response.status(500);
        response.body("Error submitting feedback");
        LOGGER.debug("Feedback submission failed", e);
    });

    enableRouteOverview();
}

From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java

@Test
public void testASMTPServerAvailability() throws UnknownHostException, IOException, MessagingException {
    MimeMessage msg = new MimeMessage(Session.getDefaultInstance(new Properties()));
    msg.setFrom(new InternetAddress("alert@srotya.com"));
    msg.setRecipient(RecipientType.TO, new InternetAddress("alert@srotya.com"));
    msg.setSubject("test mail");
    msg.setContent("Hello", "text/html");
    Transport.send(msg);/*from  www  .  j  ava 2  s .co  m*/
    MailService ms = new MailService();
    ms.init(new HashMap<>());
    Alert alert = new Alert();
    alert.setBody("test");
    alert.setId((short) 0);
    alert.setMedia("test");
    alert.setSubject("test");
    alert.setTarget("alert@srotya.com");
    ms.sendMail(alert);
    assertEquals(2, AllQATests.getSmtpServer().getReceivedEmailSize());
    System.err.println("Mail sent");
}

From source file:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;//from   w  ww  .j av  a  2s.com
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}