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:io.uengine.mail.MailAsyncService.java

@Async
public void passwd(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/auth/passwdConfirm?userid={}&token={}",
                    new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/passwd.vm", "UTF-8", model);

    try {/*w  w  w.j av  a2s.com*/
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from w  w w . j  av a 2s . co  m
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java

private void sendMessage(final String subject, final String content) {
    try {//from  w w  w .  j  a  v a  2  s . co m
        Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator)
                : Session.getInstance(smtpProps);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setSubject(subject);
        msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses));
        msg.setText(content, UTF_8.name(), "html");

        Transport.send(msg);
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailPassed(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {

    try {/* w  w  w . j  a va 2 s  .com*/

        //Get properties object    
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        //get Session   
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "anda.cristea");
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));
            //message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

            message.setSubject(subject);
            // message.setText(msg);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText("Raport teste automate");

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(filename);

            messageBodyPart.setDataHandler(new DataHandler(source));

            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (Exception ex) {
            System.out.println("eroare trimitere email-uri");
            System.out.println(ex.getMessage());

        }

    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /* w  w w .j  ava 2 s .  co  m*/
 * @param fromAddress
 * @param recipients
 *            - fully qualified recipient address
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient,
        final String[] toRecipients, final String subject, final String body, final String messageType) {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipients == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) StringUtils.join(toRecipients);
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address[] toAddresses = new Address[toRecipients.length];
        for (int i = 0; i < toAddresses.length; i++) {
            toAddresses[i] = new InternetAddress(toRecipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, toAddresses);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java

/**
 * ??//from w  w  w  .jav  a2  s .c  om
 * @param entry ??
 */
public void send(final AlarmEntry entry) {
    if (entry == null) {
        // ??null???????
        LOGGER.log(LogMessageCodes.NO_SEND_INFORMATION_MESSAGE);
        return;
    }
    if (!this.config_.isSendMail()) {
        return;
    }

    try {
        // ??
        MimeMessage message = createMailMessage(this.config_, entry);

        // ??
        Transport.send(message);
    } catch (Exception exception) {
        String message = exception.getMessage();
        LOGGER.log(LogMessageCodes.SENDING_MAIL_ERROR_MESSAGE, exception, message);
    }
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

/**
 * @param session the applications current session.
 * @throws EmailMessageException in response to any other type of exception.
 *//*from  www.  j ava 2s  . co m*/
@SuppressWarnings({ "ConstantConditions" })
protected void send(Session session) throws EmailMessageException {
    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        //set some of the basic attributes.
        msg.setFrom(fromAddress);
        msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        if (replyToAddress.isEmpty() == false) {
            msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress));
        }

        // create the Multipart and add set it as the content of the message
        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // create and fill the HTML part of the messgae if it exists
        if (html != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(html, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);
        }

        // create and fill the text part of the messgae if it exists
        if (text != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(text, "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        if (html == null && text == null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText("", "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        // remove any nulls from the list of attachments.
        while (attachments.remove(null)) {
            /* keep going */ }

        // Attach any files that we have, making sure that they exist first
        for (File file : attachments) {
            if (file.exists() == false) {
                throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
            } else {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }

        // send the message
        Transport.send(msg);

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception sending email\n" + toString(), ex);
    }
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public void sendMail(String from, String to, String subject, String messageText,
        Map<Object, Object> extraHeaders) {
    try {//from w w w . java 2  s.co  m
        MimeMessage msg = new MimeMessage(session);
        if (from.matches(EMAIL_PATTERN)) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // set fake from address; instead, add it as part of the message
            //msg.setFrom(new InternetAddress("invalid.email.address@mailinator.com"));
            msg.setFrom(getSystemAddress());
            messageText = "From: " + from + "\n\n" + messageText;
        }
        msg.setSentDate(new Date());
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        msg.setSubject(subject, charset);
        msg.setText(messageText, charset);

        if (extraHeaders != null) {
            for (Object key : extraHeaders.keySet()) {
                String headerName = key.toString();
                String headerValue = extraHeaders.get(key).toString();

                msg.addHeader(headerName, headerValue);
            }
        }

        Transport.send(msg);
    } catch (AddressException ae) {
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        me.printStackTrace(System.out);
    }
}

From source file:eu.scape_project.planning.application.BugReport.java

/**
 * Method responsible for sending a bug report per mail.
 * //from   w  w  w  . j a v  a 2 s. co  m
 * @param userEmail
 *            email address of the user.
 * @param errorDescription
 *            error description given by the user.
 * @param exception
 *            the exception causing the bug/error.
 * @param requestUri
 *            request URI where the error occurred
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            application name
 * @param plan
 *            the plan where the exception occurred
 * @throws MailException
 *             if the bug report could not be sent
 */
public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri,
        String location, String applicationName, Plan plan) throws MailException {

    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(config.getString("mail.feedback")));

        message.setSubject("[" + applicationName + "] from " + location);

        StringBuilder builder = new StringBuilder();
        // Date
        builder.append("Date: ").append(DATE_FORMAT.format(new Date())).append("\n\n");

        // User info
        if (user == null) {
            builder.append("No user available.\n\n");
        } else {
            builder.append("User: ").append(user.getUsername()).append("\n");
            if (user.getUserGroup() != null) {
                builder.append("Group: ").append(user.getUserGroup().getName()).append("\n");
            }
        }
        builder.append("UserMail: ").append(userEmail).append("\n\n");

        // Plan
        if (plan == null) {
            builder.append("No plan available.").append("\n\n");
        } else {
            builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n");
            builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n");
        }

        // Description
        builder.append("Description:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(errorDescription).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");

        // Request URI
        builder.append("Request URI: ").append(requestUri).append("\n\n");

        // Exception
        if (exception == null) {
            builder.append("No exception available.").append("\n");
        } else {
            builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n");
            builder.append("Exception message: ").append(exception.getMessage()).append("\n");

            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer));

            builder.append("Stacktrace:\n");
            builder.append(SEPARATOR_LINE);
            builder.append(writer.toString());
            builder.append(SEPARATOR_LINE);
        }

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

        Transport.send(message);
        log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(),
                config.getString("mail.feedback"));

        String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.";
        Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO",
                userMessage, user);
        try {
            utx.begin();
            em.persist(notification);
            utx.commit();
        } catch (Exception e) {
            log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e);
        }

    } catch (MessagingException e) {
        throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to "
                + config.getString("mail.feedback"), e);
    }
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 * ? E-mail ?.//from  w w w.  j  a v  a2  s .  c  o m
 *
 * @param request    ?  web-
 * @param exception ?
 * @return , ? ??? ? ?
 */
private String sendEmailToAdmin(HttpServletRequest request, Exception exception) {
    InternetAddress mail;
    String adminEmailAddress = configuration.getAdminEmailAddress();

    try {
        mail = new InternetAddress(adminEmailAddress, true);
    } catch (AddressException e) {
        return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress;
    }
    StringBuilder text = new StringBuilder();

    if (exception.getMessage() == null) {
        text.append(exception.getClass().getName());
    } else {
        text.append(exception.getMessage());
    }
    text.append("\n\n");

    Template tmpl = Template.getTemplate(request);
    //    text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri"));
    String mainUrl = "<unknown>";

    mainUrl = configuration.getMainUrl();

    text.append("Main URL: ").append(mainUrl).append(request.getServletPath());

    if (request.getQueryString() != null) {
        text.append('?').append(request.getQueryString()).append('\n');
    }
    text.append('\n');

    text.append("IP: " + request.getRemoteAddr() + '\n');

    text.append(" Headers: ");
    Enumeration enu = request.getHeaderNames();
    while (enu.hasMoreElements()) {
        String paramName = (String) enu.nextElement();
        text.append("\n         ").append(paramName).append(": ").append(request.getHeader(paramName));
    }
    text.append("\n\n");

    StringWriter exceptionStackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(exceptionStackTrace));
    text.append(exceptionStackTrace.toString());

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    try {
        emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));
        emailMessage.addRecipient(Message.RecipientType.TO, mail);
        emailMessage.setSubject("Linux.org.ru: " + exception.getClass());
        emailMessage.setSentDate(new Date());
        emailMessage.setText(text.toString(), "UTF-8");
    } catch (Exception e) {
        logger.error("An error occured while creating e-mail!", e);
        return EMAIL_NOT_SENT;
    }
    try {
        Transport.send(emailMessage);
        return EMAIL_SENT;
    } catch (Exception e) {
        return EMAIL_NOT_SENT;
    }
}