Example usage for javax.mail Message setText

List of usage examples for javax.mail Message setText

Introduction

In this page you can find the example usage for javax.mail Message setText.

Prototype

public void setText(String text) throws MessagingException;

Source Link

Document

A convenience method that sets the given String as this part's content with a MIME type of "text/plain".

Usage

From source file:com.gazbert.bxbot.core.mail.EmailAlerter.java

public void sendMessage(String subject, String msgContent) {

    if (sendEmailAlertsEnabled) {

        final Session session = Session.getInstance(smtpProps, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpConfig.getAccountUsername(),
                        smtpConfig.getAccountPassword());
            }//from  w ww.ja  v  a2s .co m
        });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(smtpConfig.getFromAddress()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpConfig.getToAddress()));
            message.setSubject(subject);
            message.setText(msgContent);

            LOG.info(() -> "About to send following Email Alert with message content: " + msgContent);
            Transport.send(message);

        } catch (MessagingException e) {
            // not much we can do here, especially if the alert was critical - the bot is shutting down; just log it.
            LOG.error("Failed to send Email Alert. Details: " + e.getMessage(), e);
        }
    } else {
        LOG.warn("Email Alerts are disabled. Not sending the following message: Subject: " + subject
                + " Content: " + msgContent);
    }
}

From source file:info.raack.appliancedetection.common.email.SMTPEmailSender.java

public void sendGeneralEmail(String recipientEmail, String subject, String body) {
    Session session = Session.getDefaultInstance(emailProperties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from w w  w  . j  a v a  2  s.  co  m*/
    });

    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject(subject + (!environment.equals("prod") ? " [" + environment + "]" : ""));
        message.setText(body);
    } catch (Exception e) {
        throw new RuntimeException("Could not create message", e);
    }

    emailQueue.add(message);
}

From source file:org.capelin.mvc.mail.SMTPMailSender.java

protected boolean send(String recipient, String body, boolean html) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", serverName);
    Session session = Session.getInstance(props, null);
    props.put("mail.from", sender);
    Message msg = new MimeMessage(session);
    try {//from  w ww  .j av a2 s .  c o m
        msg.setSubject(subject);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        if (html) {
            msg.setContent(new String(body.getBytes(), "iso-8859-1"), "text/html; charset=iso-8859-1");
        } else {
            msg.setText(body);
        }
        // Send the message:
        Transport.send(msg);
        log.debug("Email send to: " + sender);
        return true;
    } catch (MessagingException e) {
        log.info("Email Sending failed due to " + e);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:net.timbusproject.extractors.pojo.CallBack.java

public void sendEmail(String to, String subject, String body) {
    final String fromUser = fromMail;
    final String passUser = password;
    Properties props = new Properties();
    props.put("mail.smtp.host", smtp);
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    props.put("mail.smtp.auth", mailAuth);
    props.put("mail.smtp.port", port);
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromUser, passUser);
        }//from w  w  w  .  ja  va  2  s .  c  om
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromUser));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java

/**
 * Fill the body of a message already created.
 * The result message depends on the information given. 
 * //from w  w w  .  ja v a  2  s  .co m
 * @param message
 * @param text
 * @param html
 * @param parts
 * @return The composed message
 * @throws MessagingException
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
public static Message composeMessage(Message message, String text, String html, List parts)
        throws MessagingException, IOException {

    MimeBodyPart txtPart = null;
    MimeBodyPart htmlPart = null;
    MimeMultipart mimeMultipart = null;

    if (text == null && html == null) {
        text = "";
    }
    if (text != null) {
        txtPart = new MimeBodyPart();
        txtPart.setContent(text, "text/plain");
    }
    if (html != null) {
        htmlPart = new MimeBodyPart();
        htmlPart.setContent(html, "text/html");
    }
    if (html != null && text != null) {
        mimeMultipart = new MimeMultipart();
        mimeMultipart.setSubType("alternative");
        mimeMultipart.addBodyPart(txtPart);
        mimeMultipart.addBodyPart(htmlPart);
    }

    if (parts == null || parts.isEmpty()) {
        if (mimeMultipart != null) {
            message.setContent(mimeMultipart);
        } else if (html != null) {
            message.setText(html);
            message.setHeader("Content-type", "text/html");
        } else if (text != null) {
            message.setText(text);
        }
    } else {
        MimeBodyPart bodyPart = new MimeBodyPart();
        if (mimeMultipart != null) {
            bodyPart.setContent(mimeMultipart);
        } else if (html != null) {
            bodyPart.setText(html);
            bodyPart.setHeader("Content-type", "text/html");
        } else if (text != null) {
            bodyPart.setText(text);
        }
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
        for (Object attachment : parts) {
            if (attachment instanceof FileItem) {
                multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment));
            } else {
                multipart.addBodyPart((BodyPart) attachment);
            }
        }
        message.setContent(multipart);
    }

    message.saveChanges();
    return message;

}

From source file:org.infoglue.common.util.mail.MailService.java

/**
 *
 *//*from w  w  w.  jav a  2  s. c  om*/
private Message createMessage(String from, String to, String subject, String content) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);

        message.setContent(content, "text/html");
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        message.setSubject(subject);
        message.setText(content);
        message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}

From source file:webreader.WebReader.java

private void sendEmail(String inputMessage) {
    //---User login information
    final String username = email;
    final String password = emailPassword;

    //---Sets server for gmail
    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");

    //---Creates a new session
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);

        }/*  www.j a  v a  2 s . c  o m*/

    });
    //---Try catch loop for sending an email
    //---Sends error email to the sender if catch is engaged.
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject("Your grades have been updated");
        message.setText(inputMessage);
        Transport.send(message);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        emailSent = "E-mail was sent: " + dateFormat.format(date);
        System.out.println(emailSent);
    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //---Used code from https://www.youtube.com/watch?v=sHC8YgW21ho
    //---for the above method
}

From source file:mupomat.view.PodrskaLozinka.java

private void posaljiEmail() {

    final String username = "mupomat@gmail.com";
    final String password = "lesnibokysr187";

    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() {
        @Override/*from  ww  w. ja va2s.  c  o m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("mupomat@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(txtEmail.getText().trim()));
        message.setSubject("MUPomat podrka");

        message.setText("Nova lozinka: " + generiranaLozinka
                + "\nMolimo Vas da nakon prijave promjenite lozinku radi sigurnosti.\nHvala.");

        Transport.send(message);
        this.dispose();
        JOptionPane.showMessageDialog(rootPane, "Lozinka je uspjeno poslana na Vau e-mail adresu!",
                "MUPomat: Podrka", JOptionPane.INFORMATION_MESSAGE);

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

}

From source file:org.openengsb.connector.email.internal.abstraction.JavaxMailAbstraction.java

@Override
public void send(MailProperties properties, String subject, String textContent, String receiver) {
    try {// w ww. j  a  v a  2 s  . c o m
        if (!(properties instanceof MailPropertiesImp)) {
            throw new RuntimeException("This implementation works only with internal mail properties");
        }
        MailPropertiesImp props = (MailPropertiesImp) properties;

        Session session = getSession(props);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(props.getSender()));
        message.setRecipients(RecipientType.TO, InternetAddress.parse(receiver));
        message.setSubject(buildSubject(props, subject));
        message.setText(textContent);
        send(message, session);
    } catch (Exception e) {
        throw new DomainMethodExecutionException(e);
    }
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }/*from   www  . j a v  a  2 s  . c om*/
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}