List of usage examples for javax.mail.internet MimeMessage addRecipient
public void addRecipient(RecipientType type, Address 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); }/*w ww .j a v a 2 s .co 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:isl.FIMS.utils.Utils.java
public static boolean sendEmail(String to, String subject, String context) { boolean isSend = false; try {//from w ww .ja v a 2 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:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry/* w ww .j a v a 2 s . c o m*/ * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:org.ktunaxa.referral.server.command.test.TestEmailCommand.java
@Override public void execute(TestEmailRequest request, TestEmailResponse response) throws Exception { final String from = "rms@ktunaxa.org"; final String to = request.getTo(); if (null == to) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to"); }/*from w w w.ja v a2 s . c o m*/ MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setSubject("Test"); mimeMessage.setText("Testing RMS"); } }; mailSender.send(preparator); }
From source file:easyproject.service.Mail.java
public void sendMail() { Properties props = new Properties(); props.put("mail.debug", "true"); props.put("mail.smtp.auth", true); props.put("mail.smtp.starttls.enable", true); props.put("mail.smtp.host", servidorSMTP); props.put("mail.smtp.port", puerto); Session session = Session.getInstance(props, null); try {/*from www . jav a 2s.c o m*/ MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino)); message.setSubject(asunto); message.setSentDate(new Date()); message.setContent(mensaje, "text/html; charset=utf-8"); Transport tr = session.getTransport("smtp"); tr.connect(servidorSMTP, usuario, password); message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:easyproject.utils.SendMail.java
@Override public void run() { Properties props = new Properties(); props.put("mail.debug", "true"); props.put("mail.smtp.auth", true); props.put("mail.smtp.starttls.enable", true); props.put("mail.smtp.host", servidorSMTP); props.put("mail.smtp.port", puerto); Session session = Session.getInstance(props, null); try {//ww w. j a va 2 s.c o m MimeMessage message1 = new MimeMessage(session); message1.addRecipient(Message.RecipientType.TO, new InternetAddress(destino)); message1.setSubject(asunto); message1.setSentDate(new Date()); message1.setContent(mensaje, "text/html; charset=utf-8"); Transport tr = session.getTransport("smtp"); tr.connect(servidorSMTP, usuario, password); message1.saveChanges(); tr.sendMessage(message1, message1.getAllRecipients()); tr.close(); } catch (MessagingException e) { e.printStackTrace(); } }
From source file:io.starter.datamodel.Sys.java
/** * // www .jav a 2 s.co 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: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 {// w ww .j a v a2s.c o m 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) { } }
From source file:com.jive.myco.seyren.core.service.notification.EmailNotificationService.java
private MimeMessage createMimeMessage(Email email) throws AddressException, MessagingException { MimeMessage mail = mailSender.createMimeMessage(); InternetAddress senderAddress = new InternetAddress(email.getFrom()); mail.addRecipient(RecipientType.TO, new InternetAddress(email.getTo())); mail.setSender(senderAddress);/*from ww w . ja v a2 s . com*/ mail.setFrom(senderAddress); mail.setText(email.getMessage()); mail.setSubject(email.getSubject()); mail.addHeader("Content-Type", "text/html; charset=UTF-8"); return mail; }
From source file:org.openiam.idm.srvc.msg.service.MailSender.java
public void send(Message msg) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); try {//from ww w . j a v a 2s . c o m message.setFrom(msg.getFrom()); message.addRecipient(javax.mail.Message.RecipientType.TO, msg.getTo()); message.setSubject(msg.getSubject()); message.setText(msg.getBody()); Transport.send(message); log.info("Message successfully sent."); } catch (MessagingException me) { log.error(me); me.printStackTrace(); } }