Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);/*from  w  w w  .j a v  a2s  . c  om*/
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:com.linuxbox.enkive.statistics.StatsReportEmailer.java

public void sendReport() {

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", mailHost);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try { // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        for (String toAddress : to.split(";")) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        }//from w w w. ja va2 s. com

        // Set Subject: header field
        message.setSubject("Enkive Status Report");

        // Now set the actual message
        message.setText(buildReport());

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        LOGGER.warn("Error sending statistics report email", mex);
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;/*from w ww  .  ja v a  2 s.  c o m*/

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {//  w w w. j  av a 2 s .c o m
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:org.modelibra.util.Emailer.java

/**
 * Sends an email./*from  w w  w  .ja  v a 2s. c  o m*/
 * 
 * @throws dmLite
 *             exception if there is a problem
 */
public void send() throws ModelibraException {
    try {
        MimeMessage message = new MimeMessage(emailSession);
        InternetAddress fromIA = new InternetAddress(from);
        message.setFrom(fromIA);
        InternetAddress toIA = new InternetAddress(to);
        message.addRecipient(Message.RecipientType.TO, toIA);
        message.setSubject(subject);
        message.setText(content);
        emailStore.connect(outServer, code, password);
        Transport.send(message);
        emailStore.close();
    } catch (MessagingException e) {
        throw new ModelibraException("Could not send an email: " + e.getMessage());
    } catch (IllegalStateException e) {
        throw new ModelibraException("Could not send an email: " + e.getMessage());
    }
}

From source file:ftpclient.FTPManager.java

public boolean sendUserMail(String uploadedFileName) {
    if (settings != null) {
        try {//ww w .ja  v  a 2s .c o  m
            String userEmail = db.getUserEmail(uid);
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.host", settings.getSenderEmailHost());
            props.setProperty("mail.smtp.auth", "true");
            //            props.put("mail.smtp.starttls.enable", "true");
            //            props.put("mail.smtp.port", "587");
            Session s = Session.getDefaultInstance(props, new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getSenderLogin(),
                            new String(settings.getSenderPassword()));
                }
            });
            MimeMessage msg = new MimeMessage(s);
            msg.setFrom(settings.getSenderEmail());
            msg.addRecipients(Message.RecipientType.TO, userEmail);
            msg.setSubject("FTP action");
            msg.setText("You have succesfully uploaded file " + uploadedFileName);
            Transport.send(msg);
            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:com.brienwheeler.svc.email.impl.EmailService.java

/**
 * This is a private method (rather than having the public template method
 * call the public non-template method) to prevent inaccurate MonitoredWork
 * operation counts.//from   w  w  w  .j a v a2s .  c om
 * 
 * @param recipient
 * @param subject
 * @param body
 */
private void doSendEmail(EmailAddress recipient, String subject, String body) {
    ValidationUtils.assertNotNull(recipient, "recipient cannot be null");
    subject = ValidationUtils.assertNotEmpty(subject, "subject cannot be empty");
    body = ValidationUtils.assertNotEmpty(body, "body cannot be empty");

    try {
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(fromAddress.getAddress()));
        message.setRecipients(Message.RecipientType.TO, recipient.getAddress());
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
        log.info("sent email to " + recipient.getAddress() + " (" + subject + ")");
    } catch (MessagingException e) {
        throw new ServiceOperationException(e);
    }
}

From source file:org.awknet.commons.mail.Mail.java

public void send() throws AddressException, MessagingException, FileNotFoundException, IOException {
    int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size();
    if (count == 0)
        return;/*from  w w w .ja  v a  2 s.c  o m*/

    deleteDuplicates();

    Properties javaMailProperties = new Properties();

    if (fileName.equals("") || fileName == null)
        fileName = DEFAULT_PROPERTIES_FILE;

    javaMailProperties.load(getClass().getResourceAsStream(fileName));

    final String mailUsername = javaMailProperties.getProperty("mail.autentication.username");
    final String mailPassword = javaMailProperties.getProperty("mail.autentication.password");
    final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from");

    Session session = Session.getInstance(javaMailProperties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUsername, mailPassword);
        }
    });

    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mailFrom));
    msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray());
    msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray());
    msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray());
    msg.setSentDate(new Date());
    msg.setSubject(mailSubject);
    msg.setText(mailText, "UTF-8", "html");
    // msg.setText(mailText); //OLD WAY
    new Thread(new Runnable() {
        public void run() {
            try {
                Transport.send(msg);
                Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!");
            } catch (MessagingException ex) {
                Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex);
            }
        }
    }).start();
}

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

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {//from  w  w  w .  j a v a  2  s.com
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java

/** sendEmail method sends email after receiving input parameters */
@Override//ww w.  j  a  v a 2  s  .c o m
public void sendEmail(String fromEmail, String toEmail, String subject, String body,
        List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");

    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }

    List<File> tempFiles = new LinkedList<>();

    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();

        Properties properties = createSessionProperties();

        Session session = Session.getDefaultInstance(properties);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        Holder<Long> bytesWritten = new Holder<>(0L);

        for (Pair<String, InputStream> attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);

            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }

        mimeMessage.setContent(multipart);

        send(mimeMessage);

        LOGGER.debug("Email sent to " + toEmail);

    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}