List of usage examples for javax.mail.internet MimeBodyPart attachFile
public void attachFile(String file) throws IOException, MessagingException
From source file:sendfile.java
public static void main(String[] args) { if (args.length != 5) { System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false"); System.exit(1);//from ww w .j a v a 2 s. co m } String to = args[0]; String from = args[1]; String host = args[2]; String filename = args[3]; boolean debug = Boolean.valueOf(args[4]).booleanValue(); String msgText1 = "Sending a file.\n"; String subject = "Sending a file"; // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getInstance(props, null); session.setDebug(debug); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgText1); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.attachFile(filename); /* * Use the following approach instead of the above line if * you want to control the MIME type of the attached file. * Normally you should never need to do this. * FileDataSource fds = new FileDataSource(filename) { public String getContentType() { return "application/octet-stream"; } }; 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); // set the Date: header msg.setSentDate(new Date()); /* * If you want to control the Content-Transfer-Encoding * of the attached file, do the following. Normally you * should never need to do this. * msg.saveChanges(); mbp2.setHeader("Content-Transfer-Encoding", "base64"); */ // send the message Transport.send(msg); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } } catch (IOException ioex) { ioex.printStackTrace(); } }
From source file:msgsend.java
public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/*from w w w .ja va 2s . co m*/ String mailer = "msgsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; /* * Process command line arguments. */ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]"); System.exit(1); } else { break; } } try { /* * Prompt for To and Subject, if not specified. */ if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } /* * Initialize the JavaMail Session. */ Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); /* * Construct the message and send it. */ Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); /* * Save a copy of the message, if requested. */ if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:smtpsend.java
public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;// w w w. j av a2 s. c o m String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; boolean ssl = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { ssl = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); if (mailhost != null) props.put("mail.smtp.host", mailhost); if (auth) props.put("mail.smtp.auth", "true"); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * * Transport.send(msg); * * But we're going to use some SMTP-specific features for demonstration * purposes so we need to manage the Transport object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:smtpsend.java
/** * Example of how to extend the SMTPTransport class. * This example illustrates how to issue the XACT * command before the SMTPTransport issues the DATA * command.//from w ww .j a v a 2 s . co m * public static class SMTPExtension extends SMTPTransport { public SMTPExtension(Session session, URLName url) { super(session, url); // to check that we're being used System.out.println("SMTPExtension: constructed"); } protected synchronized OutputStream data() throws MessagingException { if (supportsExtension("XACCOUNTING")) issueCommand("XACT", 250); return super.data(); } } */ public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null; String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; String prot = "smtp"; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; /* * Process command line arguments. */ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { prot = "smtps"; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { /* * Prompt for To and Subject, if not specified. */ if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } /* * Initialize the JavaMail Session. */ Properties props = System.getProperties(); if (mailhost != null) props.put("mail." + prot + ".host", mailhost); if (auth) props.put("mail." + prot + ".auth", "true"); /* * Create a Provider representing our extended SMTP transport * and set the property to use our provider. * Provider p = new Provider(Provider.Type.TRANSPORT, prot, "smtpsend$SMTPExtension", "JavaMail demo", "no version"); props.put("mail." + prot + ".class", "smtpsend$SMTPExtension"); */ // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); /* * Register our extended SMTP transport. * session.addProvider(p); */ /* * Construct the message and send it. */ Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * Transport.send(msg); * * But we're going to use some SMTP-specific features for * demonstration purposes so we need to manage the Transport * object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(prot); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); /* * Save a copy of the message, if requested. */ if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { /* * Handle SMTP-specific exceptions. */ if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java
protected void setBlob(Blob blob, String id) throws MessagingException, IOException { MimeBodyPart part = new MimeBodyPart(); if (blob instanceof HasFile) { part.attachFile(((HasFile) blob).getFile()); } else {// w ww . j a v a 2 s . c o m part.setDataHandler(new DataHandler(new BlobDataSource(blob))); part.setFileName(blob.getFileName()); } part.setHeader("Content-Type", blob.getMimeType()); part.setHeader("Content-Transfer-Encoding", "binary"); int length = blob.getLength(); if (length > -1) { part.setHeader("Content-Length", Integer.toString(length)); } part.setContentID(id); mp.addBodyPart(part); }
From source file:it.ozimov.springboot.templating.mail.service.EmailServiceImpl.java
public MimeMessage send(final @NonNull Email email, final @NonNull String template, final Map<String, Object> modelObject, final @NonNull InlinePicture... inlinePictures) throws CannotSendEmailException { email.setSentAt(new Date()); final MimeMessage mimeMessage = toMimeMessage(email); try {/*from w ww .ja va 2 s. co m*/ final MimeMultipart content = new MimeMultipart("related"); String text = templateService.mergeTemplateIntoString(template, fromNullable(modelObject).or(ImmutableMap.of())); for (final InlinePicture inlinePicture : inlinePictures) { final String cid = UUID.randomUUID().toString(); //Set the cid in the template text = text.replace(inlinePicture.getTemplateName(), "cid:" + cid); //Set the image part final MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile(inlinePicture.getFile()); imagePart.setContentID('<' + cid + '>'); imagePart.setDisposition(MimeBodyPart.INLINE); imagePart.setHeader("Content-Type", inlinePicture.getImageType().getContentType()); content.addBodyPart(imagePart); } //Set the HTML text part final MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(text, email.getEncoding().displayName(), "html"); content.addBodyPart(textPart); mimeMessage.setContent(content); javaMailSender.send(mimeMessage); } catch (IOException e) { log.error("The template file cannot be read", e); throw new CannotSendEmailException( "Error while sending the email due to problems with the template file", e); } catch (TemplateException e) { log.error("The template file cannot be processed", e); throw new CannotSendEmailException( "Error while processing the template file with the given model object", e); } catch (MessagingException e) { log.error("The mime message cannot be created", e); throw new CannotSendEmailException( "Error while sending the email due to problems with the mime content", e); } return mimeMessage; }
From source file:com.cosmicpush.plugins.smtp.EmailMessage.java
/** * @param session the applications current session. * @throws EmailMessageException in response to any other type of exception. *//*from w w w . jav a2 s. c om*/ @SuppressWarnings({ "ConstantConditions" }) protected void send(Session session) throws EmailMessageException { try { // create a message MimeMessage msg = new MimeMessage(session); //set some of the basic attributes. msg.setFrom(fromAddress); msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses)); msg.setSubject(subject); msg.setSentDate(new Date()); if (replyToAddress.isEmpty() == false) { msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress)); } // create the Multipart and add set it as the content of the message Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // create and fill the HTML part of the messgae if it exists if (html != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(html, "UTF-8", "html"); multipart.addBodyPart(bodyPart); } // create and fill the text part of the messgae if it exists if (text != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text, "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } if (html == null && text == null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("", "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } // remove any nulls from the list of attachments. while (attachments.remove(null)) { /* keep going */ } // Attach any files that we have, making sure that they exist first for (File file : attachments) { if (file.exists() == false) { throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist."); } else { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(file); multipart.addBodyPart(attachmentPart); } } // send the message Transport.send(msg); } catch (EmailMessageException ex) { throw ex; } catch (Exception ex) { throw new EmailMessageException("Exception sending email\n" + toString(), ex); } }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }/*from w w w . ja va2 s .c om*/ }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
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 ww w .ja v a 2 s . co 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:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
private void addMtomPart(MimeMultipart mp, RequestableHttpVariable variable, Object httpVariableValue) throws IOException, MessagingException { String stringValue = ParameterUtils.toString(httpVariableValue); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName());/*from w ww .j a v a 2s . c om*/ String cid = variable.getMtomCid(stringValue); Engine.logBeans.debug("(HttpConnector) Prepare the MTOM attachment with cid: " + cid + ". Converting the path '" + stringValue + "' to '" + filepath + "'"); MimeBodyPart bp = new MimeBodyPart(); bp.attachFile(filepath); bp.setContentID(cid); mp.addBodyPart(bp); }