Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

In this page you can find the example usage for javax.mail Transport send.

Prototype

public static void send(Message msg) throws MessagingException 

Source Link

Document

Send a message.

Usage

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifySubscriptionDeleted(TemporaryMailContainer container) {
    try {//from  w w w.  j a  v a  2  s  .co m
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        Subscription obj = container.getObj();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s
        //maybe nice to use a template rather then sending raw xml.
        org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription();
        MappingModelToApi.mapSubscription(obj, api);
        String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES);
        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
        attachment.setFileName("uddiNotification.xml");
        mp.addBodyPart(attachment);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey()));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:org.jkcsoft.java.mail.Emailer.java

/**
 * The final funnel point method that actually uses Java Mail (javax.mail.*)
 * API to send the message.//from  www . j  a  va 2s  . c o m
 *
 * @throws MessagingException
 */
private void _sendMsg(InternetAddress[] to, InternetAddress[] bccList, InternetAddress from, String subject,
        String msgBody, String strMimeType) throws MessagingException {
    if (Strings.isEmpty(msgBody)) {
        msgBody = "(no email body; see subject)";
    }
    Session session = Session.getDefaultInstance(javaMailProps, null);
    Message msg = new MimeMessage(session);
    msg.setRecipients(Message.RecipientType.TO, to);
    if (bccList != null) {
        msg.setRecipients(Message.RecipientType.BCC, bccList);
    }
    msg.setFrom(from);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setContent(msgBody, strMimeType);
    boolean doTrySend = true;
    int numTries = 0;
    while (doTrySend) {
        numTries++;
        try {
            Transport.send(msg);
            log.info("Sent email; subject=" + subject + " to " + to[0].getAddress() + " ");
            doTrySend = false;
        } catch (MessagingException me) {
            log.warn("Try " + numTries + " of " + MAXTRIES + " failed:", me);
            if (numTries == MAXTRIES) {
                log.error("Failed to send email", me);
                throw me;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                LogHelper.error(this, "Retry sleep interrupted", e1);
            }
            doTrySend = numTries < MAXTRIES;
        }
    }
}

From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java

/**
 * Se encarga de enviar el mensaje de correo electronico *
 *///from  w  w w .  j a va  2  s .c o  m
public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException {
    try {
        Session session;
        Properties properties = System.getProperties();
        properties.put("mail.host", emdto.getHost());
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.port", emdto.getPort());
        properties.put("mail.smtp.starttls.enable", emdto.getStarttls());
        if (emdto.getUser() != null && emdto.getPassword() != null) {
            properties.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emdto.getUser(), emdto.getPassword());
                }
            });
        } else {
            properties.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(properties);
        }

        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask()));
        message.setSubject(emdto.getSubject());

        for (String to : emdto.getToList()) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
        if (emdto.getCcList() != null) {
            for (String cc : emdto.getCcList()) {
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
        }
        if (emdto.getCcoList() != null) {
            for (String cco : emdto.getCcoList()) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco));
            }
        }

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage());
        multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (emdto.getFilePaths() != null) {
            for (String filePath : emdto.getFilePaths()) {
                File file = new File(filePath);
                if (file.exists()) {
                    dataSource = new FileDataSource(file);
                    bodyPart = new MimeBodyPart();
                    bodyPart.setDataHandler(new DataHandler(dataSource));
                    bodyPart.setFileName(file.getName());
                    multipart.addBodyPart(bodyPart);
                }
            }
        }

        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception",
                ex);
        throw new BusinessException(ex);
    }
    return Boolean.TRUE;
}

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

@Override
public void sendSimpleMail(String[] address, String from, String title, String content) {
    LOG.debug("sendEmail() to: " + Arrays.toString(address));
    if (address == null || address.length == 0) {
        LOG.error("the address is empty!");
        return;/*w  w w. j a  va  2  s .co  m*/
    }
    try {
        Address[] addressArray = new Address[address.length];
        int index = 0;
        for (String str : address) {
            addressArray[index++] = new InternetAddress(str);
        }
        MimeMessage msg = getMessage(addressArray, from, content, title);
        if (m_bag.m_fromAddress != 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 " + Arrays.toString(address));

    } catch (MessagingException e) {
        LOG.error("Exception occured while trying to send notification to: " + Arrays.toString(address), e);
        LOG.debug("Details:", e);
    }
}

From source file:eu.scape_project.pw.idp.UserManager.java

/**
 * Sends the user a link to reset the password.
 * //w w  w.  ja  va2  s  . com
 * @param user
 *            the user
 * @param serverString
 *            host and port of the server
 * @throws CannotSendMailException
 *             if the password reset mail could not be sent
 */
public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException {
    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()));
        message.setSubject("Planningsuite password recovery");

        StringBuilder builder = new StringBuilder();
        builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n");
        builder.append("You have requested help recovering the password for the Plato user ");
        builder.append(user.getUsername()).append(".\n\n");
        builder.append("Please use the following link to reset your Planningsuite password: \n");
        builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken());
        builder.append("\n\n--\n");
        builder.append("Your Planningsuite team");

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Sent password reset mail to " + user.getEmail());

    } catch (Exception e) {
        log.error("Error at sending password reset mail to {}", user.getEmail());
        throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail());
    }
}

From source file:it.infn.ct.security.utilities.LDAPCleaner.java

private void sendUserRemainder(UserRequest ur, int days) {
    javax.mail.Session session = null;//w w w .  j a  v  a 2  s .  com
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

        Message mailMsg = new MimeMessage(session);
        mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"), rb.getString("IdPAdmin")));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(getGoodMail(ur),
                ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        if (rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()) {

            String ccMail[] = rb.getString("mailCopy").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.CC, mailCCopy);
        }

        if (days > 0) {
            mailMsg.setSubject(
                    rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailNotificationBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        } else {
            mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days)));
            mailMsg.setText(rb.getString("mailDeleteBody")
                    .replaceAll("_USER_", ur.getTitle() + " " + ur.getGivenname() + " " + ur.getSurname())
                    .replace("_DAYS_", Integer.toString(days)));
        }
        Transport.send(mailMsg);

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Sends a mail message. The content must be provided as MimeBodyPart objects.
 *
 * @param from      Sender's email address.
 * @param to        Recipient's email address.
 * @param cc        Email address for CC.
 * @param bcc       Email address for BCC.
 * @param subject   Subject text for the email.
 * @param bodyParts The body parts to insert into the message.
 * @throws SystemException        if an unexpected error occurs.
 * @throws ConfigurationException if a configuration error occurs.
 *///  w w  w.  j a va  2s .  c  om
public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts)
        throws ConfigurationException, SystemException {

    initEventLog();

    try {
        Properties props = new Properties();

        Configuration config = Aksess.getConfiguration();
        String host = config.getString("mail.host");
        if (host == null) {
            throw new ConfigurationException("mail.host");
        }

        // I noen tilfeller nsker vi at all epost skal g til en testadresse
        String catchAllTo = config.getString("mail.catchall.to");
        boolean catchallExists = catchAllTo != null && catchAllTo.contains("@");
        if (catchallExists) {
            StringBuilder prefix = new StringBuilder(" (original recipient: " + to);
            if (cc != null) {
                prefix.append(", cc: ").append(cc);
            }
            if (bcc != null) {
                prefix.append(", bcc: ").append(bcc);
            }
            prefix.append(") ");
            subject = prefix + subject;
            to = catchAllTo;
            cc = null;
            bcc = null;
        }

        props.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(props);

        boolean debug = config.getBoolean("mail.debug", false);
        if (debug) {
            session.setDebug(true);
        }

        // Opprett message, sett attributter
        MimeMessage message = new MimeMessage(session);
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress[] = InternetAddress.parse(to);

        message.setFrom(fromAddress);

        if (toAddress.length > 1) {
            message.setRecipients(Message.RecipientType.BCC, toAddress);
        } else {
            message.setRecipients(Message.RecipientType.TO, toAddress);
        }
        if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }

        message.setSubject(subject, "ISO-8859-1");
        message.setSentDate(new Date());

        Multipart mp = new MimeMultipart();
        for (MimeBodyPart bodyPart : bodyParts) {
            mp.addBodyPart(bodyPart);
        }
        message.setContent(mp);

        // Send meldingen
        Transport.send(message);

        eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null);

        // Logg sending
        log.info("Sending email to " + to + " with subject " + subject);
    } catch (MessagingException e) {
        String errormessage = "Subject: " + subject + " | Error: " + e.getMessage();
        eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null);
        log.error("Error sending mail", e);
        throw new SystemException("Error sending email to : " + to + " with subject " + subject, e);
    }
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*  w w  w  . ja  v  a2s  .c  o  m*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;/*  ww w  .  ja v  a2s.c om*/
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:pt.ist.fenix.api.SupportFormResource.java

private void sendEmail(String from, String subject, String body, SupportBean bean) {
    Properties props = new Properties();
    props.put("mail.smtp.host", Objects
            .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {/*from   w w w . j a  v  a  2 s .  co m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);

        Multipart multipart = new MimeMultipart();
        {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multipart.addBodyPart(messageBodyPart);
        }

        if (!Strings.isNullOrEmpty(bean.attachment)) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType)));
            messageBodyPart.setFileName(bean.fileName);
            multipart.addBodyPart(messageBodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}