Example usage for javax.mail.internet MimeMessage MimeMessage

List of usage examples for javax.mail.internet MimeMessage MimeMessage

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage MimeMessage.

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java

private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed
    // TODO add your handling code here:

    int selectedRow = productTable.getSelectedRow();
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select a Product from the Table");
        return;/*from  w  ww .  j  a va2  s . c o m*/
    }

    Product product = (Product) productTable.getValueAt(selectedRow, 0);
    int quantity = (Integer) quantitySpinner.getValue();
    if (quantity == 0) {
        JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!");
        return;
    }

    if (product != null) {
        updateQuantity(product, quantity, SUBTRACT);
    }
    String medName = product.getProdName();

    Employee patient = (Employee) patientCombo1.getSelectedItem();
    patient.getMedicalRecord().setMedicinePrescribed(medName);
    String email = patient.getEmail();

    if (email.trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!");
        return;
    }

    if (isValidEmailAddress(email)) {
        String uuid = UUID.randomUUID().toString();
        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");

        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");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24");
            }

        }

        );
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Prescribed Medicines");
            message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:"
                    + quantity + '\n' + "The unique barcode is:" + uuid);
            Transport.send(message);
            populateTable();
            JOptionPane.showMessageDialog(null, "message sent");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "message failed");
        }

    } else {
        JOptionPane.showMessageDialog(null, "Invalid Email Id");
        return;
    }

    //        String uuid = UUID.randomUUID().toString();
    //        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");
    //        
    //        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");
    //
    //            Session  session = Session.getDefaultInstance(props,
    //                    new javax.mail.Authenticator(){
    //                        protected PasswordAuthentication getPasswordAuthentication(){
    //      return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24");
    //                    }
    //   
    //            }
    //
    //   );
    //        try{
    //            Message message = new MimeMessage(session);
    //            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
    //            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
    //            message.setSubject("Prescribed Medicines");
    //            message.setText("The medicine Prescribed is :" +medName + '\n'+
    //                            "The Quantity authorized is:"+quantity + '\n'+
    //                            "The unique barcode is:"+uuid);
    //                Transport.send(message);
    //                    populateTable();
    //                    JOptionPane.showMessageDialog(null,"message sent");
    //            }catch(Exception e){
    //                JOptionPane.showMessageDialog(null,"message failed");
    //            }

}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT,
        String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {//w ww.j av a2  s.  c o m

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = sInfo.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false);

        String mailTxt = sInfo.getMailTxt();

        String[] recipients = findRecipients(sInfo, biobj, dataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", smptPort);

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(props, auth);
            logger.error("Session.getDefaultInstance(props, auth)");
        } else {
            session = Session.getDefaultInstance(props);
            logger.error("Session.getDefaultInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        String subject = mailSubj + " " + biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:com.funambol.email.items.manager.PopEntityManager.java

/**
 * This method creates an email with only header to save in
 * the local DB.//from  w w  w .j a  v a2 s  .  c o  m
 *
 * @param session Mail Server session
 * @param msg complete message
 * @return msgForDB Message with only header
 * @throws EntityException
 */
private Message createMessageForDB(Message msg, String from, String firstname, String lastname)
        throws EntityException {

    Message msgForDB = null;

    try {

        // save old Message-ID
        String mid = Utility.getHeaderMessageID(msg);

        msgForDB = new MimeMessage(this.pmsw.getSession());

        // header
        MessageCreator.setNewHeaderSent(msgForDB, msg, from, firstname, lastname);

        // default empty content
        msgForDB.setContent(Def.CONTENT_BODY, Def.CONTENT_CONTENTTYPE);

        msgForDB.saveChanges();

        // the save message command change the message-ID
        msgForDB.setHeader(Def.HEADER_MESSAGE_ID, mid);

    } catch (MessagingException me) {
        throw new EntityException(me);
    }

    return msgForDB;

}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    message = "Some of the appliances in your house are running inefficient." + "\n"
            + "Kindly check or replace your appliance " + "\n"
            + "Check the attachment for details or visit your account";
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", 587);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {//ww w  .ja v a 2 s.co  m
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Energy Board");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(name_attach.getText() + ".png");
        multipart.addBodyPart(messageBodyPart);
        mimeMessage.setContent(multipart);

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        System.out.println("sent");
        transport.close();
    } catch (MessagingException me) {

    }
}

From source file:mitm.application.djigzo.james.mailets.NotifyTest.java

@Test
public void testInvalidOriginator() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Notify mailet = new Notify();

    mailetConfig.setInitParameter("template", "encryption-notification.ftl");
    mailetConfig.setInitParameter("recipients", "originator");
    mailetConfig.setInitParameter("processor", "testProcessor");
    mailetConfig.setInitParameter("passThrough", "false");

    mailet.init(mailetConfig);//from   w  w w .  j  a v  a  2s .  c o m

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test\n", "text/plain");
    message.setHeader("From", "!@#$%^&*(");

    message.saveChanges();

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("recipient@example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("sender@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    assertEquals(0, listener.getSenders().size());
    assertEquals(0, listener.getRecipients().size());
    assertEquals(0, listener.getStates().size());
    assertEquals(0, listener.getMessages().size());
    assertEquals(0, listener.getMails().size());

    assertNull(mail.getState());
}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    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");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }/*www.j a v  a2  s  .  co m*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Verifies the signature of the passed signed part*/
public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType,
        X509Certificate certificate) throws Exception {
    BCCryptoHelper helper = new BCCryptoHelper();
    String signatureTransferEncoding = null;
    MimeMultipart checkPart = (MimeMultipart) signedPart.getContent();
    //it is sure that it is a signed part: set the type to multipart if the
    //parser has problems parsing it. Don't know why sometimes a parsing fails for
    //MimeBodyPart. This check looks if the parser is able to find more than one subpart
    if (checkPart.getCount() == 1) {
        MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType));
        MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null));
        possibleSignedMessage.setContent(multipart, multipart.getContentType());
        possibleSignedMessage.saveChanges();
        //overwrite the formerly found signed part
        signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage);
    }//from   w  w w  .  java  2  s  .  c om
    //get the content encoding of the signature
    MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent();
    //body part 1 is always the signature
    String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding");
    if (encodingHeader != null) {
        signatureTransferEncoding = encodingHeader[0];
    }
    return (helper.verify(signedPart, signatureTransferEncoding, certificate));
}

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

public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, InternetAddress[] to,
        InternetAddress[] cc, InternetAddress[] bcc, String subject, String body, MimeBodyPart[] parts)
        throws MessagingException {

    //Session session=getGlobalMailSession(pid.getDomainId());
    MimeMessage msg = new MimeMessage(session);
    try {//  w w  w .  jav a2 s .c  o  m
        subject = MimeUtility.encodeText(subject);
    } catch (Exception exc) {
    }
    msg.setSubject(subject);
    msg.addFrom(new InternetAddress[] { from });

    if (to != null)
        for (InternetAddress addr : to) {
            msg.addRecipient(Message.RecipientType.TO, addr);
        }

    if (cc != null)
        for (InternetAddress addr : cc) {
            msg.addRecipient(Message.RecipientType.CC, addr);
        }

    if (bcc != null)
        for (InternetAddress addr : bcc) {
            msg.addRecipient(Message.RecipientType.BCC, addr);
        }

    body = StringUtils.defaultString(body);
    MimeMultipart mp = new MimeMultipart("mixed");
    if (rich) {
        MimeMultipart alternative = new MimeMultipart("alternative");
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8"));
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)),
                MailUtils.buildPartContentType("text/plain", "UTF-8"));
        alternative.addBodyPart(mbp1);
        alternative.addBodyPart(mbp2);
        MimeBodyPart altbody = new MimeBodyPart();
        altbody.setContent(alternative);
        mp.addBodyPart(altbody);
    } else {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8"));
        mp.addBodyPart(mbp1);
    }

    if (parts != null) {
        for (MimeBodyPart part : parts)
            mp.addBodyPart(part);
    }

    msg.setContent(mp);

    msg.setSentDate(new java.util.Date());

    Transport.send(msg);
}

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

public boolean sendMsg(Identity ident, InternetAddress from, Collection<InternetAddress> to,
        Collection<InternetAddress> cc, Collection<InternetAddress> bcc, String subject, MimeMultipart part) {

    try {/*  w w  w .  ja v a2  s.c  o m*/
        subject = MimeUtility.encodeText(subject);
    } catch (Exception ex) {
    }

    try {
        MailAccount account = getAccount(ident);

        MimeMessage message = new MimeMessage(account.getMailSession());
        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());

        return sendMsg(ident, message);

    } catch (MessagingException ex) {
        logger.warn("Unable to send message", ex);
        return false;
    }
}

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 {//from ww  w  .  j a  v a  2 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);
}