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:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java

/** @see NotificationStrategy#execute(NotificationAddress[], Message) */
public final void execute(final NotificationAddress[] addresses, final Message message) {
    try {/*  w  w  w  . j av  a2  s .co  m*/
        final MailSender mailSender = getMailSender();
        //This is ugly....but if it is not a JavaMailSender it will
        //fail (for instance during tests). And the only way to
        //create a Multipartemail is through JavaMailSender
        if (mailSender instanceof JavaMailSender) {
            final JavaMailSender javaMailSender = (JavaMailSender) mailSender;
            final MimeMessage mail = javaMailSender.createMimeMessage();
            final MimeMessageHelper helper = new MimeMessageHelper(mail, true);
            helper.setFrom(getFromAddress().getEmailStr());
            helper.setTo(SimpleEmailNotificationStrategy.getEmailAddresses(addresses));
            helper.setReplyTo(getEmailAddress(message.getReplyToAddress()));
            helper.setSubject(message.getSubject());
            setContent(helper, (MultipartMessage) message);
            addHeaders(message, mail);
            javaMailSender.send(mail);
        } else {
            final SimpleMailMessage mail = new SimpleMailMessage();
            mail.setFrom(getFromAddress().getEmailStr());
            mail.setTo(getEmailAddresses(addresses));
            mail.setReplyTo(getEmailAddress(message.getReplyToAddress()));
            mail.setSubject(message.getSubject());
            mail.setText(message.getContent());
            mailSender.send(mail);
        }
    } catch (final MessagingException e) {
        throw new RuntimeException("Could not send message", e);
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Could not send message", e);
    }

}

From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

private Result sendMail(MCPackageMail mcPackageMail) {
    try {/*from w w  w  .  j  av a  2  s.c  o  m*/
        Map<String, String> statusAction = new HashMap<>();
        statusAction.put("NEW", "released");
        statusAction.put("CANCEL", "withdrawn");
        statusAction.put("UPDATE", "updated");

        String html = mcPackageMail.getMail();

        ArrayList<String> to = new ArrayList<>();
        to.add(mcPackageMail.getDestination());

        String from = mcPackageMail.getSource();
        String host = Configuration.getInstance().getSmtpHost();
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.localhost", host);
        javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

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

        for (String s : to) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
        }

        System.out.println("Destination: " + Arrays.asList(to).toString());

        message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", ""));
        message.setContent(html, "text/html");
        Transport.send(message);
        System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-"
                + mcPackageMail.getPackageVersion() + " was succesfully sent!");

    } catch (Exception ex) {
        Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex);
        result.setResultCode("1");
        result.setResultMessage(ex.getMessage());
    }

    return result;
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*from   w w w . j ava  2s. co  m*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:com.azprogrammer.qgf.controllers.HomeController.java

@RequestMapping(value = "/wbmail")
public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) {
    model.clear();/*from   ww  w .  j av a  2s.  com*/

    try {
        WBEmail email = new WBEmail();
        HttpSession session = req.getSession();
        String userName = session.getAttribute("userName").toString();
        String toAddress = req.getParameter("email");

        if (!WebUtil.isValidEmail(toAddress)) {
            throw new Exception("invalid email");

        }

        //TODO validate message contents
        email.setFromUser(userName);
        email.setToAddress(toAddress);

        WhiteBoard wb = getWhiteBoard(req);
        if (wb == null) {
            throw new Exception("Invalid White Board");
        }

        email.setWbKey(wb.getKey());
        email.setCreationTime(System.currentTimeMillis());

        Properties props = new Properties();
        Session mailsession = Session.getDefaultInstance(props, null);

        String emailError = null;
        try {
            MimeMessage msg = new MimeMessage(mailsession);
            msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live"));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            msg.setSubject("Please join the whiteboard session on " + req.getServerName());
            String msgBody = "To join " + userName
                    + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "</a>";
            msg.setText(msgBody, "UTF-8", "html");
            Transport.send(msg);

        } catch (AddressException e) {
            emailError = e.getMessage();
        } catch (MessagingException e) {
            emailError = e.getMessage();
        }

        if (emailError == null) {
            email.setStatus(WBEmail.STATUS_SENT);
        } else {
            email.setStatus(WBEmail.STATUS_ERROR);
        }

        getPM().makePersistent(email);

        if (email.getStatus() == WBEmail.STATUS_ERROR) {
            throw new Exception(emailError);
        }

        model.put("status", "ok");

    } catch (Exception e) {
        model.put("error", e.getMessage());
    }

    return doJSON(model);
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * /*from   ww w  . j  a  v a2s.  c  o  m*/
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

From source file:org.apache.mailet.base.test.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(text.get());/* w ww .j a  va  2  s.c  om*/
        mimeMessage.setContent(bodyPart, "text/plain");
    }
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (from.isPresent()) {
        mimeMessage.setFrom(from.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }
    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        mimeMessage.addHeader(header.name, header.value);
    }
    mimeMessage.saveChanges();
    return mimeMessage;
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void assignFromAddress(SendingMessage sendingMessage, MimeMessage msg) throws MessagingException {
    InternetAddress[] internetAddresses = InternetAddress.parse(sendingMessage.getFrom());
    for (InternetAddress internetAddress : internetAddresses) {
        if (StringUtils.isNotEmpty(internetAddress.getPersonal())) {
            try {
                internetAddress.setPersonal(internetAddress.getPersonal(), StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                throw new MessagingException("Unsupported encoding type", e);
            }//from   w  w w  . ja va2 s  .c  o m
        }
    }

    if (internetAddresses.length == 1) {
        msg.setFrom(internetAddresses[0]);
    } else {
        msg.addFrom(internetAddresses);
    }
}

From source file:hudson.tasks.MailSender.java

private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    msg.setContent("", "text/plain");
    msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset));
    msg.setSentDate(new Date());

    String replyTo = Mailer.descriptor().getReplyToAddress();
    if (StringUtils.isNotBlank(replyTo)) {
        msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) });
    }/*  www . j  av a2  s.c o m*/

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    String defaultSuffix = Mailer.descriptor().getDefaultSuffix();
    StringTokenizer tokens = new StringTokenizer(recipients);
    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 = Jenkins.getInstance().getItem(projectName, build.getProject(),
                    AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address

            // if not a valid address (i.e. no '@'), then try adding suffix
            if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) {
                address += defaultSuffix;
            }

            try {
                rcp.add(Mailer.StringToAddress(address, charset));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                listener.getLogger().println("Unable to send to address: " + address);
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    for (AbstractProject project : includeUpstreamCommitters) {
        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.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email/*from   w  w w .java  2s  .c  om*/
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());
    Session session = Session.getInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}