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.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/*from w  ww.  j  a v a 2  s . c om*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

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

From source file:eu.planets_project.pp.plato.action.session.ExceptionAction.java

@RaiseEvent("exceptionHandled")
public String sendMail() {
    try {//from   w ww  .jav  a 2  s  . c o m
        log.debug(body);
        Properties props = System.getProperties();
        Properties mailProps = new Properties();
        mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties"));
        props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER"));
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailProps.getProperty("FROM")));
        message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO")));
        String exceptionType = "Unknown";
        String exceptionMessage = "";
        String stackTrace = "";

        String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName();

        if (lastHandledException != null) {
            exceptionType = lastHandledException.getClass().getCanonicalName();
            exceptionMessage = lastHandledException.getMessage();
            StringWriter writer = new StringWriter();
            lastHandledException.printStackTrace(new PrintWriter(writer));
            stackTrace = writer.toString();
        }

        message.setSubject("[PlatoError] " + exceptionType + " at " + host);
        StringBuilder builder = new StringBuilder();
        builder.append("Date: " + format.format(new Date()) + "\n");
        builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n");
        builder.append("ExceptionType: " + exceptionType + "\n");
        builder.append("ExceptionMessage: " + exceptionMessage + "\n\n");

        builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n");
        builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n");
        builder.append(stackTrace);
        message.setText(builder.toString());
        message.saveChanges();
        Transport.send(message);
        this.lastHandledException = null;
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.",
                "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."));
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Bugreport couldn't be sent",
                "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. "
                        + "Please send an email to plato@ifs.tuwien.ac.at with a "
                        + "description of what you have been doing at the time of the error."
                        + "Thank you very much!"));
        return null;
    }
    return "home";
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

@Override
public Message sendMail(AppockMail appockMail) throws MessagingException {

    if (CollectionUtils.isEmpty(appockMail.getListeDestinataire())) {
        log.warn("Mail non envoy, liste des destinataires vide : " + appockMail);
        return null;
    }//from  w  w  w  .j a v  a  2s .co  m

    MimeMessage msg = new MimeMessage(mailServer);
    msg.setFrom(appockMail.getFrom() != null ? appockMail.getFrom() : defaultFrom());

    String prefixeSujet = isModeProduction() ? "" : "[TEST APPOCK] ";
    msg.setSubject(prefixeSujet + appockMail.getSujet(), configService.getEncodageSujetEmail());

    StringBuilder infoAdditionnelle = new StringBuilder();

    for (InternetAddress adresse : appockMail.getListeDestinataire()) {
        if (isModeProduction()) {
            // on est en production, envoi rel de mail au destinataire
            msg.addRecipient(Message.RecipientType.TO, adresse);
        } else {
            // en test, on envoie le mail  la personne connecte
            InternetAddress adresseTesteur = getAdresseMailDestinataireTesteur();
            if (adresseTesteur != null) {
                msg.addRecipient(Message.RecipientType.TO, adresseTesteur);
            }
            List<String> listeAdresseMail = new ArrayList<>();
            for (InternetAddress internetAddress : appockMail.getListeDestinataire()) {
                listeAdresseMail.add(internetAddress.getAddress());
            }
            infoAdditionnelle.append("En production cet email serait envoy vers ")
                    .append(StringUtils.join(listeAdresseMail, ", ")).append("<br/><hr/>");
            break;
        }
    }

    String contenuFinal = "";
    if (!StringUtils.isBlank(infoAdditionnelle.toString())) {
        contenuFinal += "<font face=\"arial\" >" + infoAdditionnelle.toString() + "</font>";
    }

    contenuFinal += "<font face=\"arial\" >" + appockMail.getContenu() + "<br/><br/></font>"
            + configService.getPiedDeMail();

    gereBonLivraisonDansMail(appockMail, msg, contenuFinal);

    if (!ArrayUtils.isEmpty(msg.getAllRecipients())) {
        Transport.send(msg);
    }

    return msg;
}

From source file:com.google.ie.web.controller.EmailController.java

/**
 * Send mail to the given email id with the provided text and subject.
 * /* ww  w  .ja va  2  s.  co  m*/
 * @param recepientEmailId email id of the recepient
 * @param emailText text of the mail
 * @param subject subject of the mail
 * @throws IdeasExchangeException
 * @throws MessagingException
 * @throws AddressException
 */
protected void sendMail(String recepientEmailId, String emailText, String subject)
        throws IdeasExchangeException, AddressException, MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    Message message = new MimeMessage(session);

    message.setRecipient(RecipientType.TO, new InternetAddress(recepientEmailId));
    message.setFrom(new InternetAddress(getAdminMailId()));

    message.setText(emailText);
    message.setSubject(subject);

    Transport.send(message);
    log.info("Mail sent successfully to : " + recepientEmailId + " for " + subject);
}

From source file:com.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail2(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from w w w.  j  av  a  2  s .c om
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Bienvenido al SISTEMA INFORM?TICO DEL REGISTRO NACIONAL DE ADOPCIONES, "
                + "sus credenciales para inscribirse al taller son las siguientes:" + "\n\n Usuario: " + user
                + "\n\n Contrasea: " + pass_plano
                //                    + "\n\n Para ingresar al sistema realizar lo siguiente, "
                //                    + "\n\n"
                //                    + "\n\n"
                //                    + "\n\n A. Click directamente en el siguiente link: "
                //                    + "\n\n"
                //                    + "\n\n       1. Click: http://app.mimp.gob.pe:8080/sirna "
                //                    + "\n\n       2. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n B. En caso no funcione el link, ingresar al sistema desde la pgina web: "
                //                    + "\n\n"
                //                    + "\n\n       1. Ingresar a la pgina web: www.mimp.gob.pe "
                //                    + "\n\n       2. En la barra de men Direcciones Generales? submen Vicemin. Pob. Vulnerables? seleccionar Adopciones? "
                //                    + "\n\n       3. Click en SIRNA Sistema Informtico del Registro Nacional de Adopciones? "
                //                    + "\n\n       4. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n A travs del SIRNA usted podr realizar las siguientes acciones: "
                //                    + "\n\n"
                //                    + "\n\n       - Inscribirse a uno de los talleres programados. "
                //                    + "\n\n       - Descargar las lecturas de su taller. "
                //                    + "\n\n       - Revisar el estado del proceso de adopcin. "
                //                    + "\n\n       - Cambiar su contrasea. "
                //                    + "\n\n"
                //                    + "\n\n Para continuar con el proceso, por favor ingresar al sistema e inscribirse a uno de los talleres programados, hasta un da antes de inicio del taller y/o las bacantes se  "
                //                    + "\n\n encuentres disponibles. "
                + "\n\n"
                + "\n\n De tener alguna complicacin y no fue posible su ingreso al sistema, comunicarse inmediatamente con la unidad de adopcin correspondiente.  "
                + "\n\n" + "\n\n Atentamente, " + "\n\n" + "\n\n Direccin General de Adopciones " + "\n\n"
                + "\n\n Ministerio de la Mujer y Poblaciones Vulnerables " + "\n\n ");

        Transport.send(message);

        /*  } catch (Exception ex) {
         */
    } catch (Exception ex) {

    }

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

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {//from w  ww.  ja va 2s. c  o m
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:com.app.mail.DefaultMailSender.java

@Override
public void sendWelcomeMessage(String emailAddress) {
    Session session = _authenticateOutboundEmailAddress();

    try {//from w w  w.java  2  s. c  om
        Message emailMessage = _populateMessage(emailAddress, "Welcome", "welcome_email.vm", session);

        Transport.send(emailMessage);
    } catch (Exception e) {
        _log.error("Unable to send welcome message", e);
    }
}

From source file:org.socraticgrid.taskmanager.MailHandler.java

private boolean sendMail(String host, String fromUser, boolean isFromUserProvider, String toUser,
        boolean isToUserProvider, String subject, String text) {
    boolean retVal = true;

    try {/*from  w  ww  .ja  va2s  .  com*/
        String fromAddr = getEmailAddr(isFromUserProvider, fromUser);
        String toAddr = getEmailAddr(isToUserProvider, toUser);

        //Get session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        Session session = Session.getInstance(props);

        //Create messages
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddr));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
        msg.setSubject(subject);
        msg.setText(text);
        msg.setHeader("X-Mailer", X_MAILER);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        log.debug("Mail was sent successfully.");
    } catch (Exception e) {
        log.error("Error sending mail.", e);
        retVal = false;
    }

    return retVal;
}

From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override/*from  w  ww  . j a  v  a2s . c o m*/
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java

public boolean send() {
    try {//from  w  w w.ja  va2s  .c  o m
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setReplyTo(new Address[] { replyToAddress });

        if (fromAddress == null) {
            msg.addFrom(new Address[] { replyToAddress });
        } else {
            msg.addFrom(new Address[] { fromAddress });
        }

        for (Recipient recipient : recipients) {
            msg.addRecipient(recipient.type, recipient.address);
        }

        msg.setSubject(subject);

        if (textContent.isEmpty()) {
            if (htmlContent.isEmpty()) {
                log.error("Message has neither text body nor HTML body");
            } else {
                msg.setContent(htmlContent, "text/html");
            }
        } else {
            if (htmlContent.isEmpty()) {
                msg.setContent(textContent, "text/plain");
            } else {
                MimeMultipart content = new MimeMultipart("alternative");
                addBodyPart(content, textContent, "text/plain");
                addBodyPart(content, htmlContent, "text/html");
                msg.setContent(content);
            }
        }

        msg.setSentDate(new Date());

        Transport.send(msg);
        return true;
    } catch (MessagingException e) {
        log.error("Failed to send message.", e);
        return false;
    }
}