List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message./*from w w w . j a va2s.c o m*/ * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this method * will generate an email message that includes subject, message and * attachments to the recipient list. You can use the convenience * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i> * and <i>createAttachmentList()</i> for parameter building assistance. * * @param aFromAddress Source email address. * @param aRecipientList List of recipient email addresses. * @param aSubject Subject of the email message. * @param aMessage Messsage./*from w w w. j a v a 2s .c om*/ * @param anAttachmentFiles List of file attachments or <i>null</i> for none. * * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a> * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a> * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage, ArrayList<String> anAttachmentFiles) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0) && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); Message mimeMessage = new MimeMessage(mMailSession); internetAddressFrom = new InternetAddress(aFromAddress); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); for (String mailAddressTo : aRecipientList) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } mimeMessage.setSubject(aSubject); // The following logic create a multi-part message and adds the attachment to it. BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(aMessage); // messageBodyPart.setContent(aMessage, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) { for (String pathFileName : anAttachmentFiles) { File attachmentFile = new File(pathFileName); if (attachmentFile.exists()) { messageBodyPart = new MimeBodyPart(); DataSource fileDataSource = new FileDataSource(pathFileName); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachmentFile.getName()); multipart.addBodyPart(messageBodyPart); } } appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage)); } else appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); mimeMessage.setContent(multipart); Transport.send(mimeMessage); } else throw new NSException("Valid from, recipient, subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:davmail.exchange.ews.EwsExchangeSession.java
/** * Get item content.//from w w w.ja va2 s . co m * * @param itemId EWS item id * @return item content as byte array * @throws IOException on error */ protected byte[] getContent(ItemId itemId) throws IOException { GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true); byte[] mimeContent = null; try { executeMethod(getItemMethod); mimeContent = getItemMethod.getMimeContent(); } catch (EWSException e) { LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage()); } if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new HttpNotFoundException("Item " + itemId + " not found"); } if (mimeContent == null) { LOGGER.warn("MimeContent not available, trying to rebuild from properties"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false); getItemMethod.addAdditionalProperty(Field.get("contentclass")); getItemMethod.addAdditionalProperty(Field.get("message-id")); getItemMethod.addAdditionalProperty(Field.get("from")); getItemMethod.addAdditionalProperty(Field.get("to")); getItemMethod.addAdditionalProperty(Field.get("cc")); getItemMethod.addAdditionalProperty(Field.get("subject")); getItemMethod.addAdditionalProperty(Field.get("date")); getItemMethod.addAdditionalProperty(Field.get("body")); executeMethod(getItemMethod); EWSMethod.Item item = getItemMethod.getResponseItem(); MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName())); mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName()))); mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName())); mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName())); mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName())); mimeMessage.setSubject(item.get(Field.get("subject").getResponseName())); String propertyValue = item.get(Field.get("body").getResponseName()); if (propertyValue == null) { propertyValue = ""; } mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); mimeMessage.writeTo(baos); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } mimeContent = baos.toByteArray(); } catch (IOException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } if (mimeContent == null) { throw new IOException("GetItem returned null MimeContent"); } } return mimeContent; }
From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;//from w ww .jav a 2 s . co m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version // Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected * PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( * StringUtil.environmentSubstitute(Const.NVL(authenticationUser, * "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword * , "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int // between 1= high // and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) sender_address = sender_name + '<' + sender_address + '>'; msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + " : ").append(getName()) .append(Const.CR); messageText.append(Const.CR); } if (includeDate) { messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":") .append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this // file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // add the part with the file in the // BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into // this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:com.tremolosecurity.proxy.auth.PasswordReset.java
private void sendEmail(SmtpMessage msg) throws MessagingException { Properties props = new Properties(); props.setProperty("mail.smtp.host", this.reset.getSmtpServer()); props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort())); props.setProperty("mail.smtp.user", reset.getSmtpUser()); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS())); //props.setProperty("mail.debug", "true"); //props.setProperty("mail.socket.debug", "true"); if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) { props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost()); }/*w w w .j a v a 2 s .com*/ if (reset.isUseSocks()) { props.setProperty("mail.smtp.socks.host", reset.getSocksHost()); props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort())); props.setProperty("mail.smtps.socks.host", reset.getSocksHost()); props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort())); } //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword)); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword()); } }); //Session session = Session.getInstance(props, null); 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); msgToSend.setText(msg.msg); msgToSend.saveChanges(); Transport.send(msgToSend); //tr.sendMessage(msg, msg.getAllRecipients()); //tr.close(); }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server// www . j av a2 s. co m * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, @SuppressWarnings("unused") final String port, @SuppressWarnings("unused") final String security, final File fileAttachment) { String userName = uName; String password = pWord; Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); Properties props = System.getProperties(); props.put("mail.smtp.host", host); //$NON-NLS-1$ props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ boolean usingSSL = false; if (usingSSL) { props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } Session session = Session.getInstance(props, null); session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.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); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } // set the Date: header msg.setSentDate(new Date()); // send the message int cnt = 0; do { cnt++; SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); fail = false; } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } //wrong username or password, get new one if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { fail = true; userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) {//the user is done return false; } // else //try again userName = userAndPass.get(0); password = userAndPass.get(1); } } finally { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } while (fail && cnt < 6); } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); //mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return false; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); ex.printStackTrace(); } if (fail) { return false; } //else return true; }
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; 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 . j a v a 2 s .c om*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Hospital Organization"); mimeMessage.setText(message); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (MessagingException me) { } }
From source file:cz.incad.vdkcommon.solr.Indexer.java
private void sendDemandMail(SolrDocument resultDoc, String id) { try {//from w ww . j a v a 2 s.co m String title = (String) resultDoc.getFieldValues("title").toArray()[0]; String pop = (String) resultDoc.getFieldValue("poptavka_ext"); JSONObject j = new JSONObject(pop); String from = opts.getString("admin.email"); Knihovna kn = new Knihovna(j.getString("knihovna")); String to = kn.getEmail(); String zaznam = j.optString("zaznam"); String code = j.optString("code"); String exemplar = j.optString("exemplar"); try { Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(opts.getString("admin.email.demand.subject")); String link = opts.getString("app.url") + "/original?id=" + id; String body = opts.getString("admin.email.demand.body").replace("${demand.title}", title) .replace("${demand.url}", link); message.setText(body); Transport.send(message); LOGGER.fine("Sent message successfully...."); } catch (MessagingException ex) { LOGGER.log(Level.SEVERE, "Error sending email to: {0}, from {1} ", new Object[] { to, from }); LOGGER.log(Level.SEVERE, null, ex); } } catch (NamingException | SQLException ex) { LOGGER.log(Level.SEVERE, null, ex); } }
From source file:au.aurin.org.controller.RestController.java
public Boolean sendEmail(final String randomUUIDString, final String password, final String email, final List<String> lstApps, final String fullName) throws IOException { final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString; logger.info("Starting sending Email to:" + email); String msg = ""; if (!fullName.equals("")) { msg = msg + "Dear " + fullName + "<br>"; }/*from w w w . j a v a 2s.c o m*/ Boolean lswWhatIf = false; if (lstApps != null) { //msg = msg + "You have been given access to the following applications: <br>"; msg = msg + "<br>You have been given access to the following applications: <br>"; for (final String st : lstApps) { if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) { lswWhatIf = true; } msg = "<br>" + msg + st + "<br>"; } } msg = msg + "<br>Your current password is : " + password + " <br> To customise the password please change it using link below: <br> <a href='" + clink + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. "; final String subject = "AURIN Workbench Access"; final String from = classmail.getFrom(); final String to = email; if (lswWhatIf == true) { msg = msg + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au"; msg = msg + "<br>For other related requests please contact one of the members of the project team."; msg = msg + "<br><br>Kind Regards,"; msg = msg + "<br>The Online WhatIf team<br>"; msg = msg + "<br><strong>Prof Christopher Pettit</strong> Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)"; msg = msg + "<br><strong>Claudia Pelizaro</strong> Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)"; msg = msg + "<br><strong>Andrew Dingjan</strong> Director, AURIN (andrew.dingjan@unimelb.edu.au)"; msg = msg + "<br><strong>Serryn Eagleson</strong> Manager Data and Business Analytics (serrynle@unimelb.edu.au)"; } else { msg = msg + "<br><br>Kind Regards,"; msg = msg + "<br>The AURIN Workbench team"; } try { final Message message = new MimeMessage(getSession()); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.addFrom(new InternetAddress[] { new InternetAddress(from) }); message.setSubject(subject); message.setContent(msg, "text/html"); ////////////////////////////////// final MimeMultipart multipart = new MimeMultipart("related"); final BodyPart messageBodyPart = new MimeBodyPart(); //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />"; //msg = msg + "<img src=\"cid:image\">"; messageBodyPart.setContent(msg, "text/html"); // add it multipart.addBodyPart(messageBodyPart); /////// second part (the image) // messageBodyPart = new MimeBodyPart(); final URL peopleresource = getClass().getResource("/logo.jpg"); logger.info(peopleresource.getPath()); // final DataSource fds = new FileDataSource( // peopleresource.getPath()); // // messageBodyPart.setDataHandler(new DataHandler(fds)); // messageBodyPart.setHeader("Content-ID", "<image>"); // // add image to the multipart // //multipart.addBodyPart(messageBodyPart); /////////// final MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile(peopleresource.getPath()); // final String cid = "1"; // imagePart.setContentID("<" + cid + ">"); imagePart.setHeader("Content-ID", "AbcXyz123"); imagePart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(imagePart); // put everything together message.setContent(multipart); //////////////////////////////// Transport.send(message); logger.info("Email sent to:" + email); } catch (final Exception mex) { logger.info(mex.toString()); return false; } return true; }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
@Test public void testEncryptSignedQuotedPrintableSoftBreaksDirectBC() throws Exception { MimeMessage message = loadMessage("qp-soft-breaks-signed.eml"); SMIMEEnvelopedGenerator envelopedGenerator = new SMIMEEnvelopedGenerator(); JceKeyTransRecipientInfoGenerator infoGenerator = new JceKeyTransRecipientInfoGenerator( encryptionCertificate);/*from w w w . j a v a2 s . co m*/ envelopedGenerator.addRecipientInfoGenerator(infoGenerator); JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder( new ASN1ObjectIdentifier("1.2.840.113549.3.7"), 0).setProvider("BC"); MimeBodyPart bodyPart = envelopedGenerator.generate(message, encryptorBuilder.build()); MimeMessage newMessage = new MimeMessage(MailSession.getDefaultSession()); newMessage.setContent(bodyPart.getContent(), bodyPart.getContentType()); newMessage.saveChanges(); File file = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC.eml"); FileOutputStream output = new FileOutputStream(file); MailUtils.writeMessage(newMessage, output); newMessage = MailUtils.loadMessage(file); assertEquals(SMIMEHeader.Type.ENCRYPTED, SMIMEHeader.getSMIMEContentType(newMessage)); File opensslOutputFileSigned = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl-signed.eml"); decryptMessage(file, privateKeyEntry.getPrivateKey(), opensslOutputFileSigned); newMessage = MailUtils.loadMessage(opensslOutputFileSigned); assertTrue(newMessage.isMimeType("multipart/signed")); File opensslOutputFile = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl.eml"); verifyMessage(opensslOutputFileSigned, rootCertificate, opensslOutputFile); newMessage = MailUtils.loadMessage(opensslOutputFile); assertTrue(newMessage.isMimeType("text/plain")); assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage)); }