List of usage examples for javax.mail.internet MimeMessage addRecipient
public void addRecipient(RecipientType type, Address address) throws MessagingException
From source file:org.squale.squalecommon.util.mail.javamail.JavaMailProviderImpl.java
/** * This method send mail/*from ww w.j ava2 s .c o m*/ * * @param sender Sender Address * @param recipients List of recipient address * @param subject Subject of the mail * @param content Content of the mail * @throws MailException Exception happened the send of the mail */ public void sendMail(String sender, String[] recipients, String subject, String content) throws MailException { // Initialization of the mail provider init(); // if there is mail configuration information if (smtpServer != null && (senderAddress != null || sender != null)) { // Properties used for sending mails Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); Session session = smtpAuthent(props); // Header message definition MimeMessage message = new MimeMessage(session); try { // If a sender argument is not null we use it if (sender != null) { message.setFrom(new InternetAddress(sender)); } // If the sender argument is null else { message.setFrom(new InternetAddress(senderAddress)); } // We send to each recipient for (int i = 0; i <= recipients.length - 1; i++) { String mailAddress = (String) recipients[i]; LOG.debug("Recipent : " + recipients[i]); message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mailAddress)); } // Body message definition message.setSubject(subject); message.setText(content, "iso-8859-1"); // Send of the mail Transport.send(message); } catch (AddressException e) { throw new MailException(e); } catch (MessagingException e) { throw new MailException(e); } } else { String message = MailMessages.getString("mail.exception.noConfig"); throw new MailException(message); } }
From source file:ee.cyber.licensing.service.MailService.java
public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId) throws MessagingException, IOException, SQLException { License license = licenseRepository.findById(licenseId); List<Contact> contacts = contactRepository.findAll(license.getCustomer()); List<String> receivers = getReceivers(mailbody, contacts); logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }//from w ww. j av a 2s. c o m }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "License dude")); //mailMessage.setReplyTo(InternetAddress.parse(email, false)); mailMessage.setSubject(mailbody.getSubject()); //String emailBody = body + "<br><br> Regards, <br>Cybernetica team"; mailMessage.setSentDate(new Date()); for (String receiver : receivers) { mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); } if (fileId != 0) { MailAttachment file = fileRepository.findById(fileId); if (file != null) { String fileName = file.getFileName(); byte[] fileData = file.getData_b(); if (fileName != null) { // Create a multipart message for attachment Multipart multipart = new MimeMultipart(); // Body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(mailbody.getBody(), "text/html"); multipart.addBodyPart(messageBodyPart); //Attachment part messageBodyPart = new MimeBodyPart(); ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); mailMessage.setContent(multipart); } } } else { mailMessage.setContent(mailbody.getBody(), "text/html"); } logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/*from w w w . j a v a2 s. com*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:it.infn.ct.chipster.Chipster.java
private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym, String user_emailAddress, String credential, String chipster_HOST) { log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]"); log.info("\n- SMTP Server = " + SMTP_HOST); log.info("\n- Sender = " + FROM); log.info("\n- Receiver = " + TO); log.info("\n- Application = " + ApplicationAcronym); log.info("\n- User's email = " + user_emailAddress); // Assuming you are sending email from localhost String HOST = "localhost"; // Get system properties Properties properties = System.getProperties(); properties.setProperty(SMTP_HOST, HOST); properties.setProperty("mail.debug", "true"); //properties.setProperty("mail.smtp.auth", "false"); // Get the default Session object. javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); try {/*from w w w. j a va2 s .com*/ // Create a default MimeMessage object. javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session); // Set From: header field of the header. message.setFrom(new javax.mail.internet.InternetAddress(FROM)); // Set To: header field of the header. message.addRecipient(javax.mail.Message.RecipientType.TO, new javax.mail.internet.InternetAddress(TO)); message.addRecipient(javax.mail.Message.RecipientType.CC, new javax.mail.internet.InternetAddress(user_emailAddress)); //new javax.mail.internet.InternetAddress("glarocca75@gmail.com")); // <== Change here! // Set Subject: header field message.setSubject(" Chipster Account Generator service notification "); Date currentDate = new Date(); currentDate.setTime(currentDate.getTime()); // Send the actual HTML message, as big as you like message.setContent("<br/><H4>" + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">" + "</H4><hr><br/>" + "<b>Description:</b> " + ApplicationAcronym + " notification service <br/><br/>" + "<i>A request to create a new temporary chipster account has been successfully sent from the LToS Science Gateway</i><br/><br/>" + "<b>Chipster Front Node:</b> " + chipster_HOST + "<br/>" + "<b>Credentials:</b> " + credential + "<br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>" + "<b>Disclaimer:</b><br/>" + "<i>This is an automatic message sent by the Catania Science Gateway (CSG) tailored for the EGI Long of Tail Science.<br/><br/>", "text/html"); // Send message javax.mail.Transport.send(message); } catch (javax.mail.MessagingException ex) { Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:it.infn.ct.downtime.Downtime.java
private void sendHTMLEmail(String TO, String FROM, String SMTP_HOST, File file) { String[] downtime_text = new String[4]; // Assuming you are sending email from localhost String HOST = "localhost"; // Get system properties Properties properties = System.getProperties(); properties.setProperty(SMTP_HOST, HOST); // Get the default Session object. javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); try {//from w w w . ja v a 2 s . c o m //Get Document Builder DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //Build Document Document document = builder.parse(file); //Normalize the XML Structure; It's just too important !! document.getDocumentElement().normalize(); //Here comes the root node Element root = document.getDocumentElement(); NodeList List = document.getElementsByTagName("DOWNTIME"); for (int i = 0; i < List.getLength(); i++) { Node node = List.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; // Downtime period downtime_text[0] = "SCHEDULED Downtime period <br/>"; downtime_text[0] += "Start of downtime \t[UCT]: " + eElement.getElementsByTagName("FORMATED_START_DATE").item(0).getTextContent() + "<br/>"; downtime_text[0] += "End of downtime \t[UCT]: " + eElement.getElementsByTagName("FORMATED_END_DATE").item(0).getTextContent() + "<br/><br/>"; // Entities in downtime downtime_text[1] = "<b><u>Entities in downtime:</u></b><br/>"; downtime_text[1] += "Server Host: " + eElement.getElementsByTagName("HOSTED_BY").item(0).getTextContent() + "<br/><br/>"; for (int k = 0; k < eElement.getElementsByTagName("SERVICE").getLength(); k++) { downtime_text[1] += "Nodes: " + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/>"; downtime_text[1] += "Service Type: " + eElement.getElementsByTagName("SERVICE_TYPE").item(k).getTextContent() + "<br/>"; downtime_text[1] += "Hosted service(s): " + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/><br/>"; } // Description downtime_text[2] = "<b><u>Description:</u></b><br/>"; downtime_text[2] += eElement.getElementsByTagName("DESCRIPTION").item(0).getTextContent() + "<br/>"; downtime_text[2] += "More details are available in this <a href=" + eElement.getElementsByTagName("GOCDB_PORTAL_URL").item(0).getTextContent() + "> link</a>" + "<br/><br/>"; // Severity downtime_text[3] = "<b><u>Severity:</u></b> "; downtime_text[3] += eElement.getElementsByTagName("SEVERITY").item(0).getTextContent() + "<br/><br/>"; // Sending notification // Create a default MimeMessage object. javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session); // Set From: header field of the header. message.setFrom(new javax.mail.internet.InternetAddress(FROM)); // Set To: header field of the header. message.addRecipient(javax.mail.Message.RecipientType.TO, new javax.mail.internet.InternetAddress(TO)); //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM)); // Set Subject: header field message.setSubject(" [EGI DOWNTIME] ANNOUNCEMENT "); Date currentDate = new Date(); currentDate.setTime(currentDate.getTime()); // Send the actual HTML message, as big as you like message.setContent("<br/><H4>" + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">" + "</H4>" + "Long Tail of Science (LToS) services in downtime<br/><br/>" + downtime_text[0] + downtime_text[1] + downtime_text[2] + downtime_text[3] + "<b><u>TimeStamp:</u></b><br/>" + currentDate + "<br/><br/>" + "<b><u>Disclaimer:</u></b><br/>" + "<i>This is an automatic message sent by the LToS Science Gateway based on Liferay technology." + "<br/><br/>", "text/html"); // Send notification to the user javax.mail.Transport.send(message); } } } catch (MessagingException ex) { Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java
private Result sendMail(MCPackageMail mcPackageMail) { try {//from w w w.j av a2s . c om Map<String, String> statusAction = new HashMap<>(); statusAction.put("NEW", "released"); statusAction.put("CANCEL", "withdrawn"); statusAction.put("UPDATE", "updated"); String html = mcPackageMail.getMail(); ArrayList<String> to = new ArrayList<>(); to.add(mcPackageMail.getDestination()); String from = mcPackageMail.getSource(); String host = Configuration.getInstance().getSmtpHost(); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.localhost", host); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (String s : to) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(s)); } System.out.println("Destination: " + Arrays.asList(to).toString()); message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", "")); message.setContent(html, "text/html"); Transport.send(message); System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-" + mcPackageMail.getPackageVersion() + " was succesfully sent!"); } catch (Exception ex) { Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex); result.setResultCode("1"); result.setResultMessage(ex.getMessage()); } return result; }
From source file:org.exoplatform.chat.server.ChatServer.java
public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject) throws Exception { String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST); String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER); String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD); String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT); 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"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(user, senderFullname)); // To get the array of addresses for (String to : toList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); }/*from www. j a v a 2 s .co m*/ message.setSubject(subject); message.setContent(htmlBody, "text/html"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } }
From source file:com.azprogrammer.qgf.controllers.HomeController.java
@RequestMapping(value = "/wbmail") public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) { model.clear();//from w ww.j a v a2 s .c om try { WBEmail email = new WBEmail(); HttpSession session = req.getSession(); String userName = session.getAttribute("userName").toString(); String toAddress = req.getParameter("email"); if (!WebUtil.isValidEmail(toAddress)) { throw new Exception("invalid email"); } //TODO validate message contents email.setFromUser(userName); email.setToAddress(toAddress); WhiteBoard wb = getWhiteBoard(req); if (wb == null) { throw new Exception("Invalid White Board"); } email.setWbKey(wb.getKey()); email.setCreationTime(System.currentTimeMillis()); Properties props = new Properties(); Session mailsession = Session.getDefaultInstance(props, null); String emailError = null; try { MimeMessage msg = new MimeMessage(mailsession); msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); msg.setSubject("Please join the whiteboard session on " + req.getServerName()); String msgBody = "To join " + userName + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "</a>"; msg.setText(msgBody, "UTF-8", "html"); Transport.send(msg); } catch (AddressException e) { emailError = e.getMessage(); } catch (MessagingException e) { emailError = e.getMessage(); } if (emailError == null) { email.setStatus(WBEmail.STATUS_SENT); } else { email.setStatus(WBEmail.STATUS_ERROR); } getPM().makePersistent(email); if (email.getStatus() == WBEmail.STATUS_ERROR) { throw new Exception(emailError); } model.put("status", "ok"); } catch (Exception e) { model.put("error", e.getMessage()); } return doJSON(model); }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;/*from w ww.java2 s . c o m*/ props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }