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:com.sonicle.webtop.mail.Service.java

public boolean sendMsg(Identity ident, Message msg) {
    if (ident == null) {
        try {//from w ww  . j a va 2 s . c  om
            ident = findIdentity((InternetAddress) (msg.getFrom()[0]));
        } catch (Exception exc) {

        }
    }
    String sentfolder = getSentFolder(ident);
    MailAccount account = getAccount(ident);
    try {
        Transport.send(msg);
        saveSent(account, msg, sentfolder);
        return true;

    } catch (Exception ex) {
        Service.logger.error("Exception", ex);
        return false;
    }

}

From source file:com.sonicle.webtop.mail.Service.java

public Exception sendMsg(String from, SimpleMessage smsg, List<JsAttachment> attachments) {
    //UserProfile profile = environment.getProfile();
    //String sentfolder = mprofile.getFolderSent();
    Identity ident = smsg.getFrom();
    /*f (ident != null ) {
       String mainfolder=ident.getMainFolder();
       if (mainfolder != null && mainfolder.trim().length() > 0) {
    String newsentfolder = mainfolder + folderSeparator + getLastFolderName(sentfolder);
    try {// www  .j a v  a2  s.c  o m
       Folder folder = getFolder(newsentfolder);
       if (folder.exists()) {
          sentfolder = newsentfolder;
       }
    } catch (MessagingException exc) {
       logger.error("Error on identity {}/{} Sent Folder", profile.getUserId(), ident.getEmail(), exc);
    }
       }
    }*/
    String sentfolder = getSentFolder(ident);
    MailAccount account = getAccount(ident);
    Exception retexc = null;
    Message msg = null;
    try {
        msg = createMessage(from, smsg, attachments, false);
        Transport.send(msg);
    } catch (Exception ex) {
        Service.logger.error("Exception", ex);
        retexc = ex;
    }

    //if sent succesful, save outgoing message
    if (retexc == null && msg != null) {
        retexc = saveSent(account, msg, sentfolder);

    }
    return retexc;

}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * Sends an email to the given id including a link to the password page. The
 * link contains the refID./*  w ww.  ja v  a2  s .c  o m*/
 * 
 * @param emailType
 *            - refers to the email that shall be sent, 0 sends an email for
 *            newly registered users, 1 sends a standard password-reset
 *            email
 * @param emailaddress
 * @param refID
 * @return
 */
public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) {

    String salutation = "";

    if (user.getGender().equalsIgnoreCase("male")) {
        salutation = "geehrter Herr " + user.getName();
    } else {
        salutation = "geehrte Frau " + user.getName();
    }

    MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"),
            emailProperties.getProperty("mail.user.password")); // Login

    Properties props = (Properties) emailProperties.clone();
    props.remove("mail.user");
    props.remove("mail.user.password");
    Session session = Session.getInstance(props, auth);

    String htmlContent = emailBody;
    htmlContent = htmlContent.replaceFirst("TITLE",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".title"));
    htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject"));
    htmlContent = htmlContent.replaceFirst("HEADER1",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1"));
    htmlContent = htmlContent.replaceFirst("MESSAGE",
            emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"));
    htmlContent = htmlContent.replaceFirst("SALUTATION", salutation);
    htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN",
            emailProperties.getProperty("mail.service.domain"));
    htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name"));
    htmlContent = htmlContent.replaceFirst("REFERER", refID);
    htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'");
    htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'");

    String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - "
            + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n"
            + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message");

    textContent = textContent.replaceFirst("TOPLEVELDOMAIN",
            emailProperties.getProperty("mail.service.domain"));
    textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name"));
    textContent = textContent.replaceFirst("REFERER", refID);
    textContent = textContent.replaceFirst("SALUTATION", salutation);
    textContent = textContent.replaceAll("<br>", "\n");

    try {

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user")));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress());
        msg.setSentDate(new Date());
        msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject"));

        Multipart mp = new MimeMultipart("alternative");

        // plaintext
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(textContent);
        mp.addBodyPart(textPart);

        // html
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlContent, "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);

        MimeBodyPart imagePart = new MimeBodyPart();
        DataSource fds = null;
        try {
            fds = new FileDataSource(
                    new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile()));
        } catch (MalformedURLException e) {
            Logger.getLogger(this.getClass()).error(e);
        }
        imagePart.setDataHandler(new DataHandler(fds));
        imagePart.setHeader("Content-ID", "header-image");
        mp.addBodyPart(imagePart);

        MimeBodyPart imagePart2 = new MimeBodyPart();
        DataSource fds2 = null;
        try {
            fds2 = new FileDataSource(
                    new File(new URL((String) emailProperties.get("mail.image.dash")).getFile()));
        } catch (MalformedURLException e) {
            Logger.getLogger(this.getClass()).error(e);
        }
        imagePart2.setDataHandler(new DataHandler(fds2));
        imagePart2.setHeader("Content-ID", "dash");
        mp.addBodyPart(imagePart2);

        msg.setContent(mp);

        Transport.send(msg);
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
        return false;
    }

    return true;
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, InternetAddress from, Collection<InternetAddress> to,
        Collection<InternetAddress> cc, Collection<InternetAddress> bcc, String subject, MimeMultipart part)
        throws MessagingException {

    try {//www. j  ava2  s.  c  o  m
        subject = MimeUtility.encodeText(subject);
    } catch (Exception ex) {
    }

    MimeMessage message = new MimeMessage(session);
    message.setSubject(subject);
    message.addFrom(new InternetAddress[] { from });

    if (to != null) {
        for (InternetAddress ia : to)
            message.addRecipient(Message.RecipientType.TO, ia);
    }
    if (cc != null) {
        for (InternetAddress ia : cc)
            message.addRecipient(Message.RecipientType.CC, ia);
    }
    if (bcc != null) {
        for (InternetAddress ia : bcc)
            message.addRecipient(Message.RecipientType.BCC, ia);
    }

    message.setContent(part);
    message.setSentDate(new java.util.Date());
    Transport.send(message);
}

From source file:org.enlacerh.util.FileUploadController.java

/**
 * Mtodo que enva los recibos de pago a cada usuario
 * @throws IOException /*from w  w w .  j av  a 2s.c o m*/
 * @throws NumberFormatException 
 * **/
public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException {
    try {
        //System.out.println("Enviando recibo");
        //System.out.println(jndimail());
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(jndimail());
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);

        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailRP"));
        //mm.setText(getMessage("mailContent"));

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = laruta + File.separator + file + ".pdf";
        javax.activation.DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        mm.setContent(multipart);

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente a :" + to);
        //System.out.println("Fin recibo");
    } catch (Exception e) {
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, "");
        FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {/*from   ww  w  .  ja  v  a  2 s  .  co m*/
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message
    if (ArgList.length == 5) {

        try {//from ww  w .j a  v a  2 s  . c o  m
            // Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String[] strArrRecipients = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent(ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}

From source file:com.cabserver.handler.Admin.java

@POST
@Path("forgot-password")
@Produces(MediaType.TEXT_HTML)/*w  ww  .j  a  v a2s.com*/
public Response forgotPassword(String jsonData) {
    // String data = "";
    HashMap<String, String> responseMap = new HashMap<String, String>();
    try {

        // log.info("forgotPassword before decoding = " + jsonData);

        jsonData = (URLDecoder.decode(jsonData, "UTF-8"));

        // log.info("forgotPassword >>" + jsonData);

        // jsonData = jsonData.split("=")[1];
        if (jsonData.contains("=")) {
            jsonData = jsonData.split("=")[1];
            // log.info("forgotPassword >> data=" + jsonData);
        }

        log.info("forgotPassword >> json data=" + jsonData);

        if (jsonData != null && jsonData.length() > 1) {

            // Gson gson = new Gson();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(jsonData);

            // LoginInfo result = new LoginInfo();
            String phone = (String) obj.get("phone");
            // String password = (String) obj.get("password");

            // log.info("phone =" + phone);
            // log.info("password =" + password);

            if (phone != null) {

                UserMaster um = DatabaseManager.getEmailIdByPhone(phone);

                if (um != null) {

                    log.info("forgotPassword >> Email fetched by phone number. HTTP code is 200.");

                    responseMap.put("code", "200");
                    responseMap.put("msg", "Password is sent to your registered E-Mail ID.");
                    responseMap.put("phone", phone);
                    // responseMap.put("password", um.getPassword());
                    // responseMap.put("mailid", um.getMailId());

                    try {

                        if (Boolean.parseBoolean(ConfigDetails.constants.get("LOCAL_MAIL_SEND"))) {

                            Message message = new MimeMessage(CacheBuilder.session);
                            message.setFrom(new InternetAddress("VikingTaxee@gmail.com"));
                            message.setRecipients(Message.RecipientType.TO,
                                    InternetAddress.parse(um.getMailId()));
                            message.setSubject("VikingTaxee Account Password Information");
                            message.setText("Dear Customer You password is : " + "\n\n " + um.getPassword());

                            Transport.send(message);

                            log.info("forgotPassword >> Password is sent to your registered E-Mail ID.");

                        } else {

                            TravelMaster tm = new TravelMaster();

                            tm.setFromMailId("VikingTaxee@gmail.com");
                            tm.setToMailId(um.getMailId());
                            tm.setSubject("VikingTaxee Account Password Information");
                            tm.setMailText(um.getPassword());
                            tm.setMailType(
                                    Integer.parseInt(ConfigDetails.constants.get("MAIL_TYPE_FORGOT_PASSWORD")));

                            CacheBuilder.mailSendingDataMap.put((long) new Random().nextInt(100000), tm);
                        }

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

                } else {
                    log.info("forgotPassword >> Password reset not done. Please call customer Care.");

                    responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
                    responseMap.put("msg",
                            "Forgot password process can not be completed. Please call customer Care.");

                }

            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (responseMap.size() < 1) {

        log.info("Login Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE")
                + ".");

        responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        responseMap.put("msg", "Server Error.");
        return Response.status(200).entity(jsonCreater(responseMap)).build();
    } else {
        return Response.status(200).entity(jsonCreater(responseMap)).build();
    }

}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {//from w  ww  .  j  a  v a  2s .c o  m
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw Context.reportRuntimeError("sendMail: " + e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call sendMail requires 5 arguments.");
    }
}

From source file:com.photon.phresco.util.Utility.java

public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }//  w  ww. jav a 2  s.c  o m
    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.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        DataSource source = new FileDataSource(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("Error.txt");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        DataSource source2 = new FileDataSource(screen);
        messageBodyPart2.setDataHandler(new DataHandler(source2));
        messageBodyPart2.setFileName("Error.jpg");
        multipart.addBodyPart(messageBodyPart2);
        MimeBodyPart mainPart = new MimeBodyPart();
        String content = "<b>Phresco framework error report<br><br>User Name:&nbsp;&nbsp;" + user
                + "<br> Email Address:&nbsp;&nbsp;" + fromAddr + "<br>Build No:&nbsp;&nbsp;" + build;
        mainPart.setContent(content, "text/html");
        multipart.addBodyPart(mainPart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}