List of usage examples for javax.mail Message saveChanges
public abstract void saveChanges() throws MessagingException;
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 ww w .j a va2 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:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java
private void sendEmail(SmtpMessage msg) throws MessagingException { Properties props = new Properties(); boolean doAuth = false; props.setProperty("mail.smtp.host", prov.getSmtpHost()); props.setProperty("mail.smtp.port", Integer.toString(prov.getSmtpPort())); if (prov.getSmtpUser() != null && !prov.getSmtpUser().isEmpty()) { logger.debug("SMTP user found '" + prov.getSmtpUser() + "', enabling authentication"); props.setProperty("mail.smtp.user", prov.getSmtpUser()); props.setProperty("mail.smtp.auth", "true"); doAuth = true;//from ww w . j a v a 2s.c o m } else { logger.debug("No SMTP user, disabling authentication"); doAuth = false; props.setProperty("mail.smtp.auth", "false"); } props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", Boolean.toString(prov.isSmtpTLS())); if (logger.isDebugEnabled()) { props.setProperty("mail.debug", "true"); props.setProperty("mail.socket.debug", "true"); } if (prov.getLocalhost() != null && !prov.getLocalhost().isEmpty()) { props.setProperty("mail.smtp.localhost", prov.getLocalhost()); } if (prov.isUseSOCKSProxy()) { props.setProperty("mail.smtp.socks.host", prov.getSocksProxyHost()); props.setProperty("mail.smtp.socks.port", Integer.toString(prov.getSocksProxyPort())); props.setProperty("mail.smtps.socks.host", prov.getSocksProxyHost()); props.setProperty("mail.smtps.socks.port", Integer.toString(prov.getSocksProxyPort())); } //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword)); Session session = null; if (doAuth) { logger.debug("Creating authenticated session"); session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(prov.getSmtpUser(), prov.getSmtpPassword()); } }); } else { logger.debug("Creating unauthenticated session"); session = Session.getInstance(props); } if (logger.isDebugEnabled()) { session.setDebugOut(System.out); session.setDebug(true); } //Transport tr = session.getTransport("smtp"); //tr.connect(); //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword); Message msgToSend = new MimeMessage(session); msgToSend.setFrom(new InternetAddress(msg.from)); msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to)); msgToSend.setSubject(msg.subject); if (msg.contentType != null) { msgToSend.setContent(msg.msg, msg.contentType); } else { msgToSend.setText(msg.msg); } msgToSend.saveChanges(); Transport.send(msgToSend); //tr.sendMessage(msg, msg.getAllRecipients()); //tr.close(); }
From source file:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtpm.csloxinfo.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/* w w w. j a va 2s . c o m*/ }); //Create data for referral java.util.Date date = new java.util.Date(); String s = providerID + (new Timestamp(date.getTime()).toString()); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } m.update(s.getBytes(), 0, s.length()); String md5 = (new BigInteger(1, m.digest()).toString(16)); String title = "You have an invitation from your friend."; String receiver = request.getParameter("email"); // StringBuilder messageContentHtml = new StringBuilder(); // messageContentHtml.append(request.getParameter("message") + "<br />\n"); // messageContentHtml.append("You can become a provider from here: " + baseUrl + "/Common/Provider/SignupReferral/" + md5); // String messageContent = messageContentHtml.toString(); String emailContent = " <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>" + " <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>" + providerName + "</b> has invited you to complete purchase via</p>" + " <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5 + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;" + " background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>" + " <p style='font-size:16px;margin:30px;'><b>" + providerName + "</b> will get 25 credit</p>" + " <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>" + " <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>" + " " + " " + " </div>"; String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(emailContent, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); mp.addBodyPart(backgroundImage); mp.addBodyPart(giftImage); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(mp); message.saveChanges(); Transport.send(message); ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()), md5, 0); referralDAO.insertNewReferral(referral); return true; }
From source file:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/*from ww w . jav a 2 s. c o m*/ }); String title = "You have an invitation from your friend."; JsonObject jsonObject = gson.fromJson(data, JsonObject.class); String content = jsonObject.get("content").getAsString(); JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray(); ArrayList<String> listEmail = new ArrayList<>(); if (sportsArray != null) { for (int i = 0; i < sportsArray.size(); i++) { listEmail.add(sportsArray.get(i).getAsString()); } } String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); String addresses = ""; for (int i = 0; i < listEmail.size(); i++) { if (i < listEmail.size() - 1) { addresses = addresses + listEmail.get(i) + ","; } else { addresses = addresses + listEmail.get(i); } } message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses)); message.setSubject(title); message.setContent(mp); message.saveChanges(); try { Transport.send(message); } catch (Exception e) { e.printStackTrace(); } System.out.println("sent"); return true; }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Fill the body of a message already created. * The result message depends on the information given. * //from w w w . j ava 2s . c o m * @param message * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Fill the body of a message already created. * The result message depends on the information given. * * @param message// w w w . j a v a 2s. co m * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain; charset=UTF-8"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html; charset=UTF-8"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.apache.hupa.server.utils.TestUtils.java
/** * Add a mock attachment to a mime message, you can specify whether the attachment * is an in-line image, and the file name * * @param message//w ww . jav a 2 s.co m * @param fileName * @param isInline * @throws IOException * @throws MessagingException */ public static void addMockAttachment(Message message, String fileName, boolean isInline) throws IOException, MessagingException { FileItem item = createMockFileItem(fileName, isInline ? "image/mock" : "mock/attachment"); BodyPart part = MessageUtils.fileitemToBodypart(item); if (isInline) part.addHeader("Content-ID", "any-id"); Multipart mpart = (Multipart) message.getContent(); mpart.addBodyPart(part); message.saveChanges(); }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * Prepares message prior to be sent via execute()-method, i.e. sets * properties such as protocol, authentication, etc. * * @return Message-object to be sent to execute()-method * @throws MessagingException/*from w ww.ja va 2s. c o m*/ * when problems constructing or sending the mail occur * @throws IOException * when the mail content can not be read or truststore problems * are detected */ public Message prepareMessage() throws MessagingException, IOException { Properties props = new Properties(); String protocol = getProtocol(); // set properties using JAF props.setProperty("mail." + protocol + ".host", smtpServer); props.setProperty("mail." + protocol + ".port", getPort()); props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication)); // set timeout props.setProperty("mail." + protocol + ".timeout", getTimeout()); props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout()); if (useStartTLS || useSSL) { try { String allProtocols = StringUtils .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " "); logger.info("Use ssl/tls protocols for mail: " + allProtocols); props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols); } catch (Exception e) { logger.error("Problem setting ssl/tls protocols for mail", e); } } if (enableDebug) { props.setProperty("mail.debug", "true"); } if (useStartTLS) { props.setProperty("mail.smtp.starttls.enable", "true"); if (enforceStartTLS) { // Requires JavaMail 1.4.2+ props.setProperty("mail.smtp.starttls.require", "true"); } } if (trustAllCerts) { if (useSSL) { props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false"); } } else if (useLocalTrustStore) { File truststore = new File(trustStoreToUse); logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse); logger.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (useSSL) { // Requires JavaMail 1.4.2+ props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { // Requires JavaMail 1.4.2+ props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtp.ssl.socketFactory.fallback", "false"); } } session = Session.getInstance(props, null); Message message; if (sendEmlMessage) { message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage))); } else { message = new MimeMessage(session); // handle body and attachments Multipart multipart = new MimeMultipart(); final int attachmentCount = attachments.size(); if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) { if (attachmentCount == 1) { // i.e. mailBody is empty File first = attachments.get(0); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(first)); message.setText(IOUtils.toString(is)); } finally { IOUtils.closeQuietly(is); } } else { message.setText(mailBody); } } else { BodyPart body = new MimeBodyPart(); body.setText(mailBody); multipart.addBodyPart(body); for (File f : attachments) { BodyPart attach = new MimeBodyPart(); attach.setFileName(f.getName()); attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath()))); multipart.addBodyPart(attach); } message.setContent(multipart); } } // set from field and subject if (null != sender) { message.setFrom(new InternetAddress(sender)); } if (null != replyTo) { InternetAddress[] to = new InternetAddress[replyTo.size()]; message.setReplyTo(replyTo.toArray(to)); } if (null != subject) { message.setSubject(subject); } if (receiverTo != null) { InternetAddress[] to = new InternetAddress[receiverTo.size()]; receiverTo.toArray(to); message.setRecipients(Message.RecipientType.TO, to); } if (receiverCC != null) { InternetAddress[] cc = new InternetAddress[receiverCC.size()]; receiverCC.toArray(cc); message.setRecipients(Message.RecipientType.CC, cc); } if (receiverBCC != null) { InternetAddress[] bcc = new InternetAddress[receiverBCC.size()]; receiverBCC.toArray(bcc); message.setRecipients(Message.RecipientType.BCC, bcc); } for (int i = 0; i < headerFields.size(); i++) { Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue(); message.setHeader(argument.getName(), argument.getValue()); } message.saveChanges(); return message; }
From source file:org.bml.util.mail.MailUtils.java
/** * Simple mail utility/*from ww w . j a v a2s.c om*/ * @param sendToAdresses email addresses to send the mail to * @param emailSubjectLine the subject of the email. * @param emailBody The body of the mail * @param smtpHost the smtp host * @param sender the mail address that is the sender * @param smtpPassword the password for the sender * @param smtpPort the port to contact the smtp server on * @return boolean true on success and false on error */ public static boolean sendMail(final String[] sendToAdresses, final String emailSubjectLine, final String emailBody, final String smtpHost, String sender, String smtpPassword, final int smtpPort) { if ((sendToAdresses == null) || (sendToAdresses.length == 0)) { return false; } if ((emailSubjectLine == null) || (emailBody == null)) { return false; } try { Address[] addresses = new Address[sendToAdresses.length]; for (int i = 0; i < sendToAdresses.length; i++) { addresses[i] = new InternetAddress(sendToAdresses[i]); } Properties props = System.getProperties(); props.setProperty("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.localhost", smtpHost); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", String.valueOf(smtpPort)); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(props, null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipients(Message.RecipientType.TO, addresses); message.setSubject(emailSubjectLine); message.setContent(emailBody, "text/plain"); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(smtpHost, sender, smtpPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error occured while sending mail.", t); } return false; } return true; }
From source file:org.openengsb.connector.email.internal.abstraction.JavaxMailAbstraction.java
private void send(Message message, Session session) throws MessagingException { log.info("sending email-message"); message.saveChanges(); Transport transport = getTransport(session); transport.sendMessage(message, message.getAllRecipients()); transport.close();/* w w w .j ava2s . c o m*/ log.info("email has been sent"); }