public static void main(String[] args) { // Get the Properties and Create a default session Properties prop = System.getProperties(); prop.setProperty("mail.server.com", "127.0.0.1"); Session session = Session.getDefaultInstance(prop); try { // Set the mail headers MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("*****@*****.**")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**")); msg.setSubject("First Mail"); // Create the mime body and attachments MimeBodyPart msgBody = new MimeBodyPart(); msgBody.setContent("Hello World", "text/html"); MimeBodyPart attFile = new MimeBodyPart(); attFile.attachFile("RecvMail.java"); Multipart partMsg = new MimeMultipart(); partMsg.addBodyPart(msgBody); partMsg.addBodyPart(attFile); msg.setContent(partMsg); Transport.send(msg); System.out.println("Message Successfully sent..."); } catch (Exception e) { e.printStackTrace(); } }
public void sendMailWithCalendar( String receivers, String subject, String body, String attachment) { log.info("Sending mail"); try { Authenticator authenticator = new Authenticator(serverDetails.userName, serverDetails.password); Session session = Session.getDefaultInstance(properties, authenticator); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(serverDetails.userName)); message.addRecipients(Message.RecipientType.TO, receivers); message.setSubject(subject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage"); messageBodyPart.setHeader("Content-ID", "calendar_message"); messageBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource(Files.readAllBytes(Paths.get(attachment)), "text/calendar"))); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); log.info("Mail sent"); } catch (Exception e) { log.severe("Could not send mail!" + e.getMessage()); } }
@Override public void sendAsHtml( String subject, String html, Collection<String> recipients, Map<String, Object> htmlParams) throws Exception { Address[] addresses = new Address[recipients.size()]; Iterator<String> iterator = recipients.iterator(); int i = 0; while (iterator.hasNext()) { addresses[i] = new InternetAddress(iterator.next()); i++; } Template template = configuration.getTemplate(html); Writer writer = new StringWriter(); template.process(htmlParams, writer); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(writer.toString(), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); Message message = new MimeMessage(session); message.setFrom(); message.setRecipients(Message.RecipientType.TO, addresses); message.setSubject(subject); message.setContent(multipart, "text/html"); Transport.send(message); }
/** Method for checking if the message has attachments. */ public boolean hasAttachments() throws java.io.IOException, MessagingException { boolean hasAttachments = false; if (message.isMimeType("multipart/*")) { Multipart mp = (Multipart) message.getContent(); if (mp.getCount() > 1) hasAttachments = true; } return hasAttachments; }
public void send() { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", SMTP_HOST_NAME); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); Transport transport; try { transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(userName)); message.setSubject(subject); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); if (!cc.equals("")) { message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc)); } if (!bcc.equals("")) { message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc)); } // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); // fill message messageBodyPart.setText(content); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); if (fList != null) { Iterator<File> i = fList.iterator(); // part two is attachment while (i.hasNext()) { File file = (File) i.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(file.getName()); multipart.addBodyPart(messageBodyPart); } } // Put parts in message message.setContent(multipart); Transport.send(message); transport.close(); } catch (Exception e) { e.printStackTrace(); } }
protected int getMessageSize(Message message, Account account) throws IOException, MessagingException { int count = 0; if (account.getLoginName().contains("aol.com") && message.getContent() instanceof Multipart) { Multipart multipart = (Multipart) message.getContent(); for (int i = 0; i < multipart.getCount(); i++) { count += multipart.getBodyPart(i).getSize(); } } else { count = message.getSize(); } return count; }
@Override public void setBody(Body body) throws MessagingException { this.mBody = body; setHeader("MIME-Version", "1.0"); if (body instanceof Multipart) { Multipart multipart = ((Multipart) body); multipart.setParent(this); setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType()); } else if (body instanceof TextBody) { setHeader( MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8", getMimeType())); setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "quoted-printable"); } }
protected void fillContent(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String text = getTemplate().getText(); String html = getTemplate().getHtml(); List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates(); try { if (html != null || !attachmentTemplates.isEmpty()) { // multipart MimeMultipart multipart = new MimeMultipart("related"); BodyPart p = new MimeBodyPart(); Multipart alternatives = new MimeMultipart("alternative"); p.setContent(alternatives, "multipart/alternative"); multipart.addBodyPart(p); // html if (html != null) { BodyPart htmlPart = new MimeBodyPart(); html = evaluateExpression(execution, html, session); htmlPart.setContent(html, "text/html; charset=UTF-8"); alternatives.addBodyPart(htmlPart); } // text if (text != null) { BodyPart textPart = new MimeBodyPart(); text = evaluateExpression(execution, text, session); textPart.setContent(text, "text/plain; charset=UTF-8"); alternatives.addBodyPart(textPart); } // attachments if (!attachmentTemplates.isEmpty()) { addAttachments(execution, multipart); } email.setContent(multipart); } else if (text != null) { // unipart text = evaluateExpression(execution, text, session); email.setText(text); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } }
public synchronized Map<String, Object[]> getParameterMap() { if (parameterMap == null) { // Two conditions: file upload ("multipart/form-data") or not if (getContentType() != null && getContentType().startsWith("multipart/form-data")) { // Special handling for multipart/form-data // Decode the multipart data parameterMap = Multipart.getParameterMapMultipart( pipelineContext, request, ServletExternalContext.DEFAULT_FORM_CHARSET_DEFAULT); } else if (portletRequest instanceof ResourceRequest) { // We encoded query parameters directly into the resource id in this case final String queryString = NetUtils.getQueryString(((ResourceRequest) portletRequest).getResourceID()); if (queryString != null) parameterMap = Collections.unmodifiableMap( StringConversions.stringArrayMapToObjectArrayMap( NetUtils.decodeQueryString(queryString, false))); else parameterMap = Collections.emptyMap(); } else { // Not a resource request, so just use native request parameters parameterMap = new HashMap<String, Object[]>(portletRequest.getParameterMap()); parameterMap.remove(WSRPURLRewriter.PathParameterName()); parameterMap = Collections.unmodifiableMap(parameterMap); } } return parameterMap; }
/** * Saves all attachments to a temp directory, and returns the directory path. Null if no * attachments. */ public File saveAttachments(Message message) throws IOException, MessagingException { File tmpDir = Files.createTempDir(); boolean foundAttachments = false; Object content = message.getContent(); if (message.isMimeType(MULTIPART_WILDCARD) && content instanceof Multipart) { Multipart mp = (Multipart) content; for (int i = 0; i < mp.getCount(); i++) { BodyPart bodyPart = mp.getBodyPart(i); if (bodyPart instanceof MimeBodyPart && isNotBlank(bodyPart.getFileName())) { MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart; mimeBodyPart.saveFile(new File(tmpDir, mimeBodyPart.getFileName())); foundAttachments = true; } } } return foundAttachments ? tmpDir : null; }
@Override public void setEncoding(String encoding) throws UnavailableStorageException { if (mBody instanceof Multipart) { ((Multipart) mBody).setEncoding(encoding); } else if (mBody instanceof TextBody) { setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding); ((TextBody) mBody).setEncoding(encoding); } }
@Override public void setCharset(String charset) throws MessagingException { if (mBody instanceof Multipart) { ((Multipart) mBody).setCharset(charset); } else if (mBody instanceof TextBody) { MimeUtility.setCharset(charset, this); ((TextBody) mBody).setCharset(charset); } }
public void send( String from, String[] recipientsTo, String[] recipientsCC, String[] recipientsBCC, String subject, String body, String[] files) { try { Properties properties = System.getProperties(); setMailServerProperties(username, password, host, properties); Session session = Session.getInstance( properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); setAllRecipients(recipientsTo, recipientsCC, recipientsBCC, message); message.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(body, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); setAttachments(files, multipart); message.setContent(multipart); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } }
private void setAttachments(String[] files, Multipart multipart) throws MessagingException { if (files != null) { for (String file : files) { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(file); multipart.addBodyPart(messageBodyPart); } } }
public static int sendMail(String toAddr, String ccAddr, String mailTitle, String mailConcept) { Session s = Session.getInstance(SendMail.props, null); s.setDebug(false); Message message = new MimeMessage(s); try { Address from = new InternetAddress(SendMail.SenderEmailAddr); message.setFrom(from); Address to = new InternetAddress(toAddr); message.setRecipient(Message.RecipientType.TO, to); if (ccAddr != null && ccAddr != "") { Address cc = new InternetAddress(ccAddr); message.setRecipient(Message.RecipientType.CC, cc); } message.setSubject(mailTitle); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(mailConcept, "text/html;charset=ISO-8859-1"); mainPart.addBodyPart(html); message.setContent(mainPart); message.setSentDate(new Date()); message.saveChanges(); Transport transport = s.getTransport(SendMail.TransprotType); transport.connect(SendMail.SMTPServerName, SendMail.SMTPUserName, SendMail.SMTPPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); // System.out.println("发送邮件,邮件地址:"+toAddr); // System.out.println("发送邮件,邮件地址:"+ccAddr); // System.out.println("标题:"+mailTitle); // System.out.println("内容:"+mailConcept); System.out.println("Email Send Success!"); return 1; } catch (Exception e) { System.out.println(e.getMessage()); return -1; } }
/** Returns the body of the message (if it's plain text). */ public String getBody() throws MessagingException, java.io.IOException { Object content = message.getContent(); if (message.isMimeType("text/plain")) { return (String) content; } else if (message.isMimeType("multipart/alternative")) { Multipart mp = (Multipart) message.getContent(); int numParts = mp.getCount(); for (int i = 0; i < numParts; ++i) { if (mp.getBodyPart(i).isMimeType("text/plain")) return (String) mp.getBodyPart(i).getContent(); } return ""; } else if (message.isMimeType("multipart/*")) { Multipart mp = (Multipart) content; if (mp.getBodyPart(0).isMimeType("text/plain")) return (String) mp.getBodyPart(0).getContent(); else return ""; } else return ""; }
public boolean send() { try { // creamos las propiedades del mail Properties propiedades = System.getProperties(); propiedades.put("mail.smtp.host", hostSmtp); propiedades.put("mail.smtp.auth", "true"); propiedades.put("mail.smtp.port", puertoSMTP); // creamos la sesión para enviar el mail SMTPAuthentication auth = new SMTPAuthentication(); Session mailSesion = Session.getInstance(propiedades, auth); // creamos el mensaje MimeMessage mens = new MimeMessage(mailSesion); // Definimos la dirección del remitente mens.setFrom(new InternetAddress(this.origen)); // creamos un array de las direcciones de los destinatarios InternetAddress[] addressTo = new InternetAddress[this.direcciones.size()]; for (int i = 0; i < this.direcciones.size(); i++) { addressTo[i] = new InternetAddress((String) this.direcciones.get(i)); } // definimos los destinatarios mens.addRecipients(Message.RecipientType.TO, addressTo); // definiemos la fecha de envio mens.setSentDate(new Date()); // Definimos el asunto mens.setSubject(asunto); Multipart multipart = new MimeMultipart(); MimeBodyPart texto = new MimeBodyPart(); texto.setContent(this.mensaje, "text/html"); multipart.addBodyPart(texto); if (this.rutaAdjunto != null) { BodyPart adjunto = new MimeBodyPart(); adjunto.setDataHandler(new DataHandler(new FileDataSource(this.rutaAdjunto))); adjunto.setFileName(this.nombreAdjunto); multipart.addBodyPart(adjunto); } // Definimos el cuerpo del mensaje mens.setContent(multipart); // Creamos el objeto transport con el método Transport transporte = mailSesion.getTransport("smtp"); // enviamos el correo transporte.send(mens); } catch (AddressException ex) { ex.printStackTrace(); return false; } catch (SendFailedException ex) { ex.printStackTrace(); return false; } catch (MessagingException ex) { ex.printStackTrace(); return false; } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
public static List<String> getText(BytesWritable value, Boolean tokenizep) throws InterruptedException { Session s = Session.getDefaultInstance(new Properties()); InputStream is = new ByteArrayInputStream(value.getBytes()); List<String> out = new ArrayList<String>(); try { MimeMessage message = new MimeMessage(s, is); message.getAllHeaderLines(); Analyzer standard_analyzer = new StandardAnalyzer(Version.LUCENE_43); Analyzer email_analyzer = new UAX29URLEmailAnalyzer(Version.LUCENE_43); Address[] fromAddrs = message.getFrom(); String fromAddrstr = ""; if (fromAddrs != null) { for (Address addr : fromAddrs) { fromAddrstr += (addr.toString() + " "); } } Address[] toAddrs = message.getAllRecipients(); String toAddrstr = ""; if (toAddrs != null) { for (Address addr : toAddrs) { toAddrstr += (addr.toString() + " "); } } String subject = message.getSubject(); String body = ""; try { Object content = message.getContent(); // System.err.println(content.getContentType()); if (content instanceof String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int i = 0; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); // System.err.println(bp.getContentType()); Object c = bp.getContent(); if (c instanceof String) { body = (String) c; } } } // people do really evil things with email, we're not sorting through it all now } catch (DecodingException e) { System.err.println("DecodingException"); } catch (UnsupportedEncodingException e) { System.err.println("UnsuportedEncodingException"); } catch (IOException e) { System.err.println("IOException"); } if (tokenizep) { List<String> fromData = new ArrayList<String>(); List<String> toData = new ArrayList<String>(); List<String> subjectData = new ArrayList<String>(); List<String> bodyData = new ArrayList<String>(); if (fromAddrstr != null) { fromData = tokenizeString(email_analyzer, fromAddrstr); } if (toAddrstr != null) { toData = tokenizeString(email_analyzer, toAddrstr); } if (subject != null) { subjectData = tokenizeString(standard_analyzer, subject); } if (body != null) { bodyData = tokenizeString(standard_analyzer, body); } out.add("FROM "); out.addAll(fromData); out.add("TO "); out.addAll(toData); out.add("SUBJECT "); out.addAll(subjectData); out.add("BODY "); out.addAll(bodyData); } else { // if not tokenizep, return list with from and subject fields only out.add(fromAddrstr); out.add(subject); } } catch (MessagingException e) { System.err.println("MessagineException"); } return out; }
public static String send(Email2Send email, Server server) throws Exception { Session session; if (server.isAuth()) { Authenticator auth = new PopAuthenticator(server.getUser(), server.getPwd()); session = Session.getInstance(getProperties(server), auth); } else { session = Session.getInstance(getProperties(server), null); } MyMessage mailMsg = new MyMessage(session); // a new email message InternetAddress[] addresses = null; try { if (email.getDestinatari() != null && email.getDestinatari().size() > 0) { addresses = InternetAddress.parse(email.getDestinatariToString(), false); mailMsg.setRecipients(Message.RecipientType.TO, addresses); } else { throw new MessagingException("The mail message requires a 'To' address."); } if (email.getCc() != null && email.getCc().size() > 0) { addresses = InternetAddress.parse(email.getCcToString(), false); mailMsg.setRecipients(Message.RecipientType.CC, addresses); } if (email.getBcc() != null && email.getBcc().size() > 0) { addresses = InternetAddress.parse(email.getBccToString(), false); mailMsg.setRecipients(Message.RecipientType.BCC, addresses); } if (email.getMittente() != null) { mailMsg.setFrom(new InternetAddress(email.getMittente())); } else { throw new MessagingException("The mail message requires a valid 'From' address."); } // if (email.getOggetto() != null) mailMsg.setSubject(email.getOggetto()); // corpo e attachment if (email.getAllegati() != null && email.getAllegati().size() > 0) { BodyPart messageBodyPart = new MimeBodyPart(); if (email.getCorpo() != null) messageBodyPart.setText(email.getCorpo()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachment for (File allegato : email.getAllegati()) { messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(allegato.getCanonicalPath()); DataHandler dataH = new DataHandler(source); messageBodyPart.setDataHandler(dataH); messageBodyPart.setFileName(allegato.getName()); multipart.addBodyPart(messageBodyPart); } mailMsg.setContent(multipart); } else { mailMsg.setContent(email.getCorpo(), "text/plain;charset=\"UTF-8\""); } mailMsg.setId("<CN" + System.currentTimeMillis() + "@giava.by/giavacms>"); // mailMsg.addHeader("Message-ID", // "111111.11199295388525.provaProvaProva"); mailMsg.setSentDate(new Date()); mailMsg.saveChanges(); // Finally, send the mail message; throws a 'SendFailedException' // if any of the message's recipients have an invalid address Transport.send(mailMsg); } catch (MessagingException e) { logger.error(e.toString()); e.printStackTrace(); return ""; } catch (Exception exc) { logger.error(exc.toString()); exc.printStackTrace(); return ""; } return mailMsg.getMessageID(); }
public static void dumpPart(Part p, biz.systempartners.claims.ClaimsViewer claimsViewer) throws Exception { if (p instanceof Message) dumpEnvelope((Message) p); /** * Dump input stream .. * * <p>InputStream is = p.getInputStream(); // If "is" is not already buffered, wrap a * BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) is = new * BufferedInputStream(is); int c; while ((c = is.read()) != -1) System.out.write(c); */ String ct = p.getContentType(); try { pr("CONTENT-TYPE: " + (new ContentType(ct)).toString()); } catch (ParseException pex) { pr("BAD CONTENT-TYPE: " + ct); } String filename = p.getFileName(); if (filename != null) pr("FILENAME: " + filename); /* * Using isMimeType to determine the content type avoids * fetching the actual content data until we need it. */ if (p.isMimeType("text/plain")) { pr("This is plain text"); pr("---------------------------"); if (!showStructure && !saveAttachments) System.out.println((String) p.getContent()); } else if (p.isMimeType("multipart/*")) { pr("This is a Multipart"); pr("---------------------------"); Multipart mp = (Multipart) p.getContent(); level++; int count = mp.getCount(); for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i), claimsViewer); level--; } else if (p.isMimeType("message/rfc822")) { pr("This is a Nested Message"); pr("---------------------------"); level++; dumpPart((Part) p.getContent(), claimsViewer); level--; } else { if (!showStructure && !saveAttachments) { /* * If we actually want to see the data, and it's not a * MIME type we know, fetch it and check its Java type. */ Object o = p.getContent(); if (o instanceof String) { pr("This is a string"); pr("---------------------------"); System.out.println((String) o); } else if (o instanceof InputStream) { pr("This is just an input stream"); pr("---------------------------"); InputStream is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { pr("This is an unknown type"); pr("---------------------------"); pr(o.toString()); } } else { // just a separator pr("---------------------------"); } } /* * If we're saving attachments, write out anything that * looks like an attachment into an appropriately named * file. Don't overwrite existing files to prevent * mistakes. */ if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) { String disp = p.getDisposition(); // many mailers don't include a Content-Disposition if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (filename == null) filename = "Attachment" + attnum++; pr("Saving attachment to file " + filename); try { File f = new File(System.getProperty("user.dir"), filename); /* if (f.exists()) // XXX - could try a series of names throw new IOException("file exists");*/ OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); if (p.isMimeType("text/xml") || p.isMimeType("application/octet-stream")) { processBrRequisitionFile( f, claimsViewer, claimsViewer.getInvoiceVector(), claimsViewer.getFilesVector()); } System.out.println("I have saved file [" + f.getAbsolutePath() + "]"); } catch (IOException ex) { pr("Failed to save attachment: " + ex); } pr("---------------------------"); } } }
public static void send(AlarmManager.Alarm alarm) { String to = Settings.GetSettingForKey(Setting.EMAIL_ADDR); // ***** smtp login details ***** // Dont save these details in a file // Strongly recommended to generate a single application access key from google // Dont use your actual password! String from = "@gmail.com"; final String username = "******"; final String password = ""; Properties props = new Properties(); props.put("mail.smtp.ssl.trust", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "465"); Session session = Session.getInstance( props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("PiSec Alarm Notice"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(alarm.toString()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); try { if (!alarm.getPictureLocation().equals("")) { File zippedImages = zipImages(alarm); String filename = zippedImages.getAbsolutePath(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } } catch (Exception e) { Logger.Log("Unable to attach zipped images!"); } message.setContent(multipart); Transport.send(message); Logger.Log("Email Sent!"); } catch (MessagingException e) { e.printStackTrace(); Logger.Log("Unable to send email! " + e.getMessage()); } }
public static void readTrainingMail(String fileNameWithPath) { InputStream is; try { is = new FileInputStream(fileNameWithPath); Properties props = System.getProperties(); props.put("mail.host", "stmp.gmail.com"); props.put("mail.transport.protocol", "stmp"); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession, is); if (message.getSubject() != null) { System.out.println("subject ---> " + message.getSubject()); } if (message.getFrom() != null) { System.out.println(message.getFrom()[0].toString()); } /** * The Message.RecipientType is divided into TO , the primary recipients -- CC ,carbon copy * recipients -- 抄送 BCC, blind carbon copy recipients-- 发送邮件副本,又不想让原始接收人知道,密抄送 */ if (message.getRecipients(MimeMessage.RecipientType.CC) != null) { System.out.println("CC : found " + message.getRecipients(Message.RecipientType.CC)); } if (message.getRecipients(Message.RecipientType.BCC) != null) { System.out.println("BCc : Found " + message.getRecipients(Message.RecipientType.BCC)); } if (message.getRecipients(Message.RecipientType.TO) != null) { System.out.println("To Found " + message.getRecipients(Message.RecipientType.TO)); Address[] AddressList = message.getRecipients(Message.RecipientType.TO); for (Address internetAddress : AddressList) { InternetAddress addr = (InternetAddress) internetAddress; System.out.println(addr.getAddress()); } } if (message.getSentDate() != null) { System.out.println("message Date : " + message.getSentDate()); } System.out.println("here is the email 's content type name"); System.out.println(message.getContentType()); System.out.println("here is the email content "); System.out.println(message.getContent()); if (message.getContentType().startsWith("multipart")) { Multipart multiPart = (Multipart) message.getContent(); for (int x = 0; x < multiPart.getCount(); x++) { BodyPart bodyPart = multiPart.getBodyPart(x); String disposition = bodyPart.getDisposition(); if (disposition != null) { String content = html2text((String) bodyPart.getContent()).trim(); System.out.println("Content : " + content); System.out.println("disposition " + disposition); } System.out.println("is email contains disposition ? "); if (disposition != null && disposition.equals(BodyPart.ATTACHMENT)) System.out.println("yes"); else System.out.println("no"); } } } catch (Exception e) { e.printStackTrace(); } }
/* * This method checks for content-type * based on which, it processes and * fetches the content of the message */ public static void writePart(Part p, MailInfo mailInfo) throws Exception { if (p instanceof Message) // Call methos writeEnvelope writeEnvelope((Message) p, mailInfo); log.info("----------------------------"); log.info("CONTENT-TYPE: " + p.getContentType()); // check if the content is plain text if (p.isMimeType("text/plain")) { log.info("This is plain text"); log.info("---------------------------"); log.info((String) p.getContent()); mailInfo.setBody(p.getContent().toString()); } // check if the content has attachment else if (p.isMimeType("multipart/*")) { log.info("This is a Multipart"); log.info("---------------------------"); Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) writePart(mp.getBodyPart(i), mailInfo); } // check if the content is a nested message else if (p.isMimeType("message/rfc822")) { log.info("This is a Nested Message"); log.info("---------------------------"); writePart((Part) p.getContent(), mailInfo); } // check if the content is an inline image else if (p.isMimeType("image/jpeg")) { log.info("--------> image/jpeg"); Object o = p.getContent(); InputStream x = (InputStream) o; ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(x, bos); NamedContent namedContent = new NamedContent(); namedContent.setName(p.getFileName()); namedContent.setType(p.getContentType()); namedContent.setContent(bos.toByteArray()); mailInfo.getAttachments().add(namedContent); } else if (p.isMimeType("image/png")) { log.info("--------> image/png"); Object o = p.getContent(); InputStream x = (InputStream) o; ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(x, bos); NamedContent namedContent = new NamedContent(); namedContent.setName(p.getFileName()); namedContent.setType(p.getContentType()); namedContent.setContent(bos.toByteArray()); mailInfo.getAttachments().add(namedContent); } else if (p.getContentType().contains("image/")) { log.info("content type" + p.getContentType()); File f = new File("image" + new Date().getTime() + ".jpg"); DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f))); com.sun.mail.util.BASE64DecoderStream test = (com.sun.mail.util.BASE64DecoderStream) p.getContent(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = test.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } else { Object o = p.getContent(); if (o instanceof String) { log.info("This is a string"); log.info("---------------------------"); log.info((String) o); } else if (o instanceof InputStream) { log.info("This is just an input stream"); log.info("---------------------------"); InputStream is = (InputStream) o; is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { log.info("This is an unknown type"); log.info("---------------------------"); log.info(o.toString()); } } }
public static boolean sendMail( String userName, String passWord, String host, String port, String starttls, String auth, boolean debug, String socketFactoryClass, String fallback, String[] to, String[] cc, String[] bcc, String subject, String text, String attachmentPath, String attachmentName) { // Object Instantiation of a properties file. Properties props = new Properties(); props.put("mail.smtp.user", userName); props.put("mail.smtp.host", host); if (!"".equals(port)) { props.put("mail.smtp.port", port); } if (!"".equals(starttls)) { props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.auth", auth); } if (debug) { props.put("mail.smtp.debug", "true"); } else { props.put("mail.smtp.debug", "false"); } if (!"".equals(port)) { props.put("mail.smtp.socketFactory.port", port); } if (!"".equals(socketFactoryClass)) { props.put("mail.smtp.socketFactory.class", socketFactoryClass); } if (!"".equals(fallback)) { props.put("mail.smtp.socketFactory.fallback", fallback); } try { Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); MimeMessage msg = new MimeMessage(session); msg.setText(text); msg.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentPath); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachmentName); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); msg.setFrom(new InternetAddress(userName)); for (int i = 0; i < to.length; i++) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } for (int i = 0; i < cc.length; i++) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i])); } for (int i = 0; i < bcc.length; i++) { msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i])); } msg.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(host, userName, passWord); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); return true; } catch (Exception mex) { mex.printStackTrace(); return false; } }
public static void dumpPart(Part p) throws Exception { if (p instanceof Message) { Message m = (Message) p; Address[] a; // FROM if ((a = m.getFrom()) != null) { for (int j = 0; j < a.length; j++) System.out.println("FROM: " + a[j].toString()); } // TO if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { for (int j = 0; j < a.length; j++) System.out.println("TO: " + a[j].toString()); } // SUBJECT System.out.println("SUBJECT: " + m.getSubject()); // DATE Date d = m.getSentDate(); System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN")); // FLAGS: Flags flags = m.getFlags(); StringBuffer sb = new StringBuffer(); Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags boolean first = true; for (int i = 0; i < sf.length; i++) { String s; Flags.Flag f = sf[i]; if (f == Flags.Flag.ANSWERED) s = "\\Answered"; else if (f == Flags.Flag.DELETED) s = "\\Deleted"; else if (f == Flags.Flag.DRAFT) s = "\\Draft"; else if (f == Flags.Flag.FLAGGED) s = "\\Flagged"; else if (f == Flags.Flag.RECENT) s = "\\Recent"; else if (f == Flags.Flag.SEEN) s = "\\Seen"; else continue; // skip it if (first) first = false; else sb.append(' '); sb.append(s); } String[] uf = flags.getUserFlags(); // get the user flag strings for (int i = 0; i < uf.length; i++) { if (first) first = false; else sb.append(' '); sb.append(uf[i]); } System.out.println("FLAGS = " + sb.toString()); } System.out.println("CONTENT-TYPE: " + p.getContentType()); /* Dump input stream InputStream is = ((MimeMessage)m).getInputStream(); int c; while ((c = is.read()) != -1) System.out.write(c); */ Object o = p.getContent(); if (o instanceof String) { System.out.println("This is a String"); System.out.println((String) o); } else if (o instanceof Multipart) { System.out.println("This is a Multipart"); Multipart mp = (Multipart) o; int count = mp.getCount(); for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i)); } else if (o instanceof InputStream) { System.out.println("This is just an input stream"); InputStream is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } }
public boolean sendMessage() { Properties properties = new Properties(); properties.put("mail.smtp.host", mailHost); properties.put("mail.from", Source); Session session = Session.getInstance(properties, null); try { Message message = new MimeMessage(session); InternetAddress[] addressTO = null; if (this.Destination != null && this.Destination.length() != 0) { StringTokenizer TOList = getTokenizer(this.Destination); addressTO = new InternetAddress[TOList.countTokens()]; for (int i = 0; i < addressTO.length; i++) { addressTO[i] = new InternetAddress(TOList.nextToken()); message.addRecipient(Message.RecipientType.TO, addressTO[i]); } } if (this.MsgCC != null && this.MsgCC.length() != 0) { StringTokenizer CCList = getTokenizer(this.MsgCC); InternetAddress[] addressCC = new InternetAddress[CCList.countTokens()]; for (int i = 0; i < addressCC.length; i++) { addressCC[i] = new InternetAddress(CCList.nextToken()); message.addRecipient(Message.RecipientType.CC, addressCC[i]); } } message.setFrom(new InternetAddress(Source)); message.setSubject(Subject); Content = getHtmlHeader() + Content + getHtmlFooter(); Content = Content.replaceAll("\\{style\\}", MailStyle); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(Content); messageBodyPart.setContent(Content, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Iterator it = this.BinaryAttachments.iterator(); while (it.hasNext()) { ByteArrayDataSource bads = (ByteArrayDataSource) it.next(); messageBodyPart = new MimeBodyPart(); // messageBodyPart.setDataHandler(new DataHandler(new FileDataSource("c:/test/tom.jpg"))); messageBodyPart.setDataHandler(new DataHandler(bads)); messageBodyPart.setFileName(bads.getName()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); Transport transport = session.getTransport(addressTO[0]); transport.addConnectionListener(new ConnectionHandler()); transport.addTransportListener(new TransportHandler()); transport.connect(); transport.send(message); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
private void doit(String[] argv) { String to = null, subject = null, from = null, replyTo = null, cc = null, bcc = null, url = null; String mailhost = null; String mailer = "MsgSend"; String protocol = null, host = null, user = null, password = null, record = null; String filename = null, msg_text = null, inline_filename = null; boolean debug = 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("-X")) { msg_text = 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")) { filename = argv[++optind]; } else if (argv[optind].equals("-i")) { inline_filename = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator (from) from = argv[++optind]; } else if (argv[optind].equals("-r")) { // reply-to replyTo = 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.err.println(USAGE_TEXT); 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(); // 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 Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); if (reply_to_list == null && replyTo != null) { reply_to_list = new InternetAddress[1]; reply_to_list[0] = new InternetAddress(replyTo); msg.setReplyTo(reply_to_list); } else msg.setReplyTo(reply_to_list); if (dis_list == null) { dis_list = new InternetAddress[1]; dis_list[0] = new InternetAddress(to); } msg.setRecipients(Message.RecipientType.TO, dis_list); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); // in-line file contents if specified if (inline_filename != null) { msg_text = readFile(inline_filename); } // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msg_text); // create the Multipart and add the text part Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); // create additional message part(s) // attach the file or files to the message if (filename != null) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); mbp1.setText(msg_text + "\n\nAttachment: " + filename); System.out.println("Added attachment: " + filename); } if (attachments != null) { Iterator i = attachments.iterator(); StringBuffer list = null; while (i.hasNext()) { String name = (String) i.next(); MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(name); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); if (list == null) { list = new StringBuffer(name); } else { list.append(", " + name); } System.out.println("Added attachment: " + name); mbp1.setText(msg_text + "\nAttachment(s): " + list); } } // add the Multipart to the message msg.setContent(mp); msg.setSubject(subject); // jgfrun collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("Mail 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) { System.err.println("Could not MsgSend.doit"); e.printStackTrace(); } } // doit
public static void sendEmailByJava(String subject, String content, List<String> address) throws MailingException { Transport transport = null; try { Smtp smtp = new Smtp(); // Create the mail session Session mailSession; mailSession = Session.getInstance(smtp.toProperties()); // Create the connection transport = mailSession.getTransport(smtp.getKindConnection()); transport.connect(smtp.getHost(), smtp.getUser(), smtp.getPassword()); InternetAddress fromAddress = null; try { fromAddress = new InternetAddress( MiddlewareProperties.NOTIFICATIONS_EMAIL_ADDRESS, "WB-API Notifications"); } catch (UnsupportedEncodingException e) { } if (address != null && !address.isEmpty()) { MimeMessage msg = new MimeMessage(mailSession); msg.setSubject(subject, "utf-8"); InternetAddress[] addressTo = new InternetAddress[address.size()]; for (int i = 0; i < address.size(); i++) { addressTo[i] = new InternetAddress(address.get(i)); } // Set recipient mail if (fromAddress != null) { msg.setFrom(fromAddress); } msg.setRecipients(Message.RecipientType.BCC, addressTo); // Set body text MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=utf-8"); // Multipart message Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); // Send the message try { transport.sendMessage(msg, msg.getAllRecipients()); } catch (MessagingException e) { logger.error(e); throw new MailingException(e); } } else { logger.debug( "Trying to send a mail to a null or empty list of recipients. This is the content of the message:\n '" + content + "'"); } logger.debug("Email sent."); } catch (Exception e) { logger.error(e); throw new MailingException(e); } finally { try { if (transport != null && transport.isConnected()) { // Close the email connection transport.close(); } } catch (MessagingException e) { logger.error(e); } } }