List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:com.emc.kibana.emailer.KibanaEmailer.java
private static void sendFileEmail(String security) { final String username = smtpUsername; final String password = smtpPassword; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); if (security.equals(SMTP_SECURITY_TLS)) { properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); } else if (security.equals(SMTP_SECURITY_SSL)) { properties.put("mail.smtp.socketFactory.port", smtpPort); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", smtpPort); }//from w ww . j av a2 s . c o m Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sourceAddress)); // Set To: header field of the header. for (String destinationAddress : destinationAddressList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress)); } // Set Subject: header field message.setSubject(mailTitle); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); StringBuffer bodyBuffer = new StringBuffer(mailBody); if (!kibanaUrls.isEmpty()) { bodyBuffer.append("\n\n"); } // Add urls info to e-mail for (Map<String, String> kibanaUrl : kibanaUrls) { // Add urls to e-mail String urlName = kibanaUrl.get(NAME_KEY); String reportUrl = kibanaUrl.get(URL_KEY); if (urlName != null && reportUrl != null) { bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n"); } } // Fill the message messageBodyPart.setText(bodyBuffer.toString()); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachments for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) { messageBodyPart = new MimeBodyPart(); String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY); String filename = kibanaScreenCapture.get(FILE_NAME_KEY); DataSource source = new FileDataSource(absoluteFilename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); logger.info("Sent mail message successfully"); } catch (MessagingException mex) { throw new RuntimeException(mex); } }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifySubscriptionDeleted(TemporaryMailContainer container) { try {/* w w w . java2 s . c om*/ Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); Subscription obj = container.getObj(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s //maybe nice to use a template rather then sending raw xml. org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription(); MappingModelToApi.mapSubscription(obj, api); String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey())); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:com.iana.boesc.utility.BOESCUtil.java
public static boolean sendEmailWithAttachments(final String emailFrom, final String subject, final InternetAddress[] addressesTo, final String body, final File attachment) { try {// w w w . j a v a2 s. c o m Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("", ""); } }); MimeMessage message = new MimeMessage(session); // Set From: header field of the header. InternetAddress addressFrom = new InternetAddress(emailFrom); message.setFrom(addressFrom); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, addressesTo); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart(); // Fill the message messageBodyPart.setText(body); messageBodyPart.setContent(body, "text/html"); // Create a multi part message Multipart multipart = new javax.mail.internet.MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new javax.mail.internet.MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); return true; } catch (Exception ex) { ex.getMessage(); return false; } }
From source file:network.thunder.server.etc.Tools.java
public static void emailException(Exception e, Message m, Channel c, Payment p, Transaction channelTransaction, Transaction t) {/*w w w . j av a 2s. c o m*/ String to = "matsjj@gmail.com"; String from = "exception@thunder.network"; String host = "localhost"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("New Critical Exception thrown.."); String text = ""; text += Tools.stacktraceToString(e); text += "\n"; if (m != null) { text += m; } text += "\n"; if (c != null) { text += c; } text += "\n"; if (p != null) { text += p; } text += "\n"; if (channelTransaction != null) { text += channelTransaction; } text += "\n"; if (t != null) { text += t; } // Now set the actual message message.setText(text); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { // mex.printStackTrace(); } }
From source file:com.email.SendEmailCrashReport.java
/** * Sends crash email to predetermined list from the database. * * Also BCCs members of XLN team for notification of errors */// w w w. j a v a2s. co m public static void sendCrashEmail() { //Get Account SystemEmailModel account = null; for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals("ERROR")) { account = acc; break; } } if (account != null) { String FROMaddress = account.getEmailAddress(); List<String> TOAddresses = SystemErrorEmailList.getActiveEmailAddresses(); String[] BCCAddressess = ("Anthony.Perk@XLNSystems.com".split(";")); String subject = "SERB 3.0 Application Daily Error Report for " + Global.getMmddyyyy().format(Calendar.getInstance().getTime()); String body = buildBody(); Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage email = new MimeMessage(session); try { for (String TO : TOAddresses) { if (EmailValidator.getInstance().isValid(TO)) { email.addRecipient(Message.RecipientType.TO, new InternetAddress(TO)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { email.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } email.setFrom(new InternetAddress(FROMaddress)); email.setSubject(subject); email.setText(body); Transport.send(email); } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } else { System.out.println("No account found to send Error Email"); } }
From source file:isl.FIMS.utils.Utils.java
public static boolean sendEmail(String to, String subject, String context) { boolean isSend = false; try {//from www . j a v a2 s. c o m String host = "smtp.gmail.com"; String user = emailAdress; String password = emailPass; String port = "587"; String from = "no-reply-" + systemName + "@gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.user", user); props.put("mail.smtp.password", password); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); // props.put("mail.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.EnableSSL.enable", "true"); // props.put("mail.smtp.socketFactory.port", port); // props.put("mail.smtp.socketFactory.class", // "javax.net.ssl.SSLSocketFactory"); // props.put("mail.smtp.port", "465"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); // To get the array of addresses message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject, "UTF-8"); message.setContent(context, "text/html; charset=UTF-8"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } isSend = true; } catch (MessagingException ex) { ex.printStackTrace(); } return isSend; }
From source file:org.masukomi.aspirin.core.Bouncer.java
/** * This generates a response to the Return-Path address, or the address of * the message's sender if the Return-Path is not available. Note that this * is different than a mail-client's reply, which would use the Reply-To or * From header.//from ww w .j a v a 2 s . c om * * @param mail * DOCUMENT ME! * @param message * DOCUMENT ME! * @param bouncer * DOCUMENT ME! * * @throws MessagingException * DOCUMENT ME! */ static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer) throws MessagingException { if (bouncer != null) { if (log.isDebugEnabled()) { log.debug("bouncing message to postmaster"); } MimeMessage orig = mail.getMessage(); //Create the reply message MimeMessage reply = (MimeMessage) orig.reply(false); //If there is a Return-Path header, if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) { //Return the message to that address, not to the Reply-To // address reply.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0])); } //Create the list of recipients in our MailAddress format Collection recipients = new HashSet(); Address[] addresses = reply.getAllRecipients(); for (int i = 0; i < addresses.length; i++) { recipients.add(new MailAddress((InternetAddress) addresses[i])); } //Change the sender... reply.setFrom(bouncer.toInternetAddress()); try { //Create the message body MimeMultipart multipart = new MimeMultipart(); //Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(message, "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); multipart.addBodyPart(part); //Add the original message as the second mime body part part = new MimeBodyPart(); part.setContent(orig.getContent(), orig.getContentType()); part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType()); multipart.addBodyPart(part); reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date())); reply.setContent(multipart); reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); } catch (IOException ioe) { throw new MessagingException("Unable to create multipart body", ioe); } //Send it off... //sendMail( bouncer, recipients, reply ); que.queMail(reply); } }
From source file:io.starter.datamodel.Sys.java
/** * //w ww. j av a2 s.c o m * @param params * @throws Exception * * */ public static void sendEmail(String url, final User from, String toEmail, Map params, SqlSession session, CountDownLatch latch) throws Exception { final CountDownLatch ltc = latch; if (from == null) { throw new ServletException("Sys.sendEmail cannot have a null FROM User."); } String fromEmail = from.getEmail(); final String fro = fromEmail; final String to = toEmail; final Map p = params; final String u = url; final SqlSession sr = session; // TODO: check message sender/recipient validity if (!checkEmailValidity(fromEmail)) { throw new RuntimeException( fromEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED"); } // TODO: check mail server if it's a valid message if (!checkEmailValidity(toEmail)) { throw new RuntimeException( toEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED"); } // message.setSubject("Testing Email From Starter.io"); // Send the actual HTML message, as big as you like // fetch the content final String content = getText(u); new Thread(new Runnable() { @Override public void run() { // Sender's email ID needs to be mentioned // String sendAccount = "$EMAIL_USER_NAME$"; // final String username = "$EMAIL_USER_NAME$", password = // "hum0rm3"; // Assuming you are sending email from localhost // String host = "gator3083.hostgator.com"; String sendAccount = "$EMAIL_USER_NAME$"; final String username = "$EMAIL_USER_NAME$", password = "$EMAIL_USER_PASS$"; // Assuming you are sending email from localhost String host = SystemConstants.EMAIL_SERVER; // Get system properties Properties props = System.getProperties(); // Setup mail server props.setProperty("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.port", "587"); // Get the default Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sendAccount)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendAccount)); // Set Subject: header field Object o = p.get("MESSAGE_SUBJECT"); message.setSubject(o.toString()); String ctx = new String(content.toString()); // TODO: String Rep on the params ctx = stringRep(ctx, p); message.setContent(ctx, "text/html; charset=utf-8"); // message.setContent(new Multipart()); // Send message Transport.send(message); Logger.log("Sending message to:" + to + " SUCCESS"); } catch (MessagingException mex) { // mex.printStackTrace(); Logger.log("Sending message to:" + to + " FAILED"); Logger.error("Sys.sendEmail() failed to send message. Messaging Exception: " + mex.toString()); } // log the data Syslog logEntry = new Syslog(); logEntry.setDescription("OK [ email sent from: " + fro + " to: " + to + "]"); logEntry.setUserId(from.getId()); logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SEND_EMAIL); logEntry.setSourceId(from.getId()); // unknown logEntry.setSourceType(SystemConstants.TARGET_TYPE_USER); logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis())); SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); SqlSession sesh = sqlSessionFactory.openSession(true); sesh.insert("io.starter.dao.SyslogMapper.insert", logEntry); sesh.commit(); if (ltc != null) ltc.countDown(); // release the latch } }).start(); }
From source file:com.eatcodesleep.web.MailRestController.java
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public String sendMail(@RequestBody final TextEmail textEmail) { javaMailSender.send((MimeMessage mimeMessage) -> { mimeMessage.setFrom(textEmail.getFromAddress()); mimeMessage.setRecipients(Message.RecipientType.TO, textEmail.getToAddressesAsCommaSeparatedString()); mimeMessage.setText(textEmail.getMessage()); });/* w w w .ja v a2 s . co m*/ return "Success!!!"; }
From source file:SendMailBean.java
public void emailPassword(String email, String memberName, String password) { String host = "mail"; String from = "w@j.com"; Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try {/*from w ww . j a v a 2s . com*/ message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject("Password Reminder"); message.setText("Hi " + memberName + ",\nYour password is: " + password + "\nregards - " + from); Transport.send(message); } catch (AddressException ae) { } catch (MessagingException me) { } }