List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:javamailclient.GmailAPI.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email./* ww w. jav a2s. c o m*/ * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Sends a mail message. The content must be provided as MimeBodyPart objects. * * @param from Sender's email address. * @param to Recipient's email address. * @param cc Email address for CC. * @param bcc Email address for BCC. * @param subject Subject text for the email. * @param bodyParts The body parts to insert into the message. * @throws SystemException if an unexpected error occurs. * @throws ConfigurationException if a configuration error occurs. *///from w ww. j a v a 2s. c o m public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts) throws ConfigurationException, SystemException { initEventLog(); try { Properties props = new Properties(); Configuration config = Aksess.getConfiguration(); String host = config.getString("mail.host"); if (host == null) { throw new ConfigurationException("mail.host"); } // I noen tilfeller nsker vi at all epost skal g til en testadresse String catchAllTo = config.getString("mail.catchall.to"); boolean catchallExists = catchAllTo != null && catchAllTo.contains("@"); if (catchallExists) { StringBuilder prefix = new StringBuilder(" (original recipient: " + to); if (cc != null) { prefix.append(", cc: ").append(cc); } if (bcc != null) { prefix.append(", bcc: ").append(bcc); } prefix.append(") "); subject = prefix + subject; to = catchAllTo; cc = null; bcc = null; } props.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(props); boolean debug = config.getBoolean("mail.debug", false); if (debug) { session.setDebug(true); } // Opprett message, sett attributter MimeMessage message = new MimeMessage(session); InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddress[] = InternetAddress.parse(to); message.setFrom(fromAddress); if (toAddress.length > 1) { message.setRecipients(Message.RecipientType.BCC, toAddress); } else { message.setRecipients(Message.RecipientType.TO, toAddress); } if (cc != null) { message.addRecipients(Message.RecipientType.CC, cc); } if (bcc != null) { message.addRecipients(Message.RecipientType.BCC, bcc); } message.setSubject(subject, "ISO-8859-1"); message.setSentDate(new Date()); Multipart mp = new MimeMultipart(); for (MimeBodyPart bodyPart : bodyParts) { mp.addBodyPart(bodyPart); } message.setContent(mp); // Send meldingen Transport.send(message); eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null); // Logg sending log.info("Sending email to " + to + " with subject " + subject); } catch (MessagingException e) { String errormessage = "Subject: " + subject + " | Error: " + e.getMessage(); eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null); log.error("Error sending mail", e); throw new SystemException("Error sending email to : " + to + " with subject " + subject, e); } }
From source file:AmazonSESSample.java
private static RawMessage getRawMessage() throws MessagingException, IOException { // JavaMail representation of the message Session s = Session.getInstance(new Properties(), null); s.setDebug(true);/*from w w w .ja v a 2s. c o m*/ MimeMessage msg = new MimeMessage(s); // Sender and recipient msg.setFrom(new InternetAddress("aravind@gofastpay.com")); InternetAddress[] address = { new InternetAddress("aravind@gofastpay.com") }; msg.setRecipients(javax.mail.Message.RecipientType.TO, address); msg.setSentDate(new Date()); // Subject msg.setSubject(SUBJECT); // Add a MIME part to the message //MimeMultipart mp = new MimeMultipart(); Multipart mp = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); //mimeBodyPart.setText(BODY); //BodyPart part = new MimeBodyPart(); //String myText = BODY; //part.setContent(URLEncoder.encode(myText, "US-ASCII"), "text/html"); //part.setText(BODY); //mp.addBodyPart(part); //msg.setContent(mp); mimeBodyPart.setContent(BODY, "text/html"); mp.addBodyPart(mimeBodyPart); msg.setContent(mp); // Print the raw email content on the console //PrintStream out = System.out; ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); //String rawString = out.toString(); //byte[] bytes = IOUtils.toByteArray(msg.getInputStream()); //ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length); //ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getEncoder().encode(rawString.getBytes())); //byteBuffer.put(bytes); //byteBuffer.put(Base64.getEncoder().encode(bytes)); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(out.toByteArray())); return rawMessage; }
From source file:com.iana.boesc.utility.BOESCUtil.java
public static boolean sendEmailWithAttachments(final String emailFrom, final String subject, final InternetAddress[] addressesTo, final String body, final File attachment) { try {//from w w w . j a va2 s .c o m Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("", ""); } }); MimeMessage message = new MimeMessage(session); // Set From: header field of the header. InternetAddress addressFrom = new InternetAddress(emailFrom); message.setFrom(addressFrom); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, addressesTo); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart(); // Fill the message messageBodyPart.setText(body); messageBodyPart.setContent(body, "text/html"); // Create a multi part message Multipart multipart = new javax.mail.internet.MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new javax.mail.internet.MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); return true; } catch (Exception ex) { ex.getMessage(); return false; } }
From source file:com.emc.kibana.emailer.KibanaEmailer.java
private static void sendFileEmail(String security) { final String username = smtpUsername; final String password = smtpPassword; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); if (security.equals(SMTP_SECURITY_TLS)) { properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); } else if (security.equals(SMTP_SECURITY_SSL)) { properties.put("mail.smtp.socketFactory.port", smtpPort); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", smtpPort); }/*ww w . ja v a2s .com*/ Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sourceAddress)); // Set To: header field of the header. for (String destinationAddress : destinationAddressList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress)); } // Set Subject: header field message.setSubject(mailTitle); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); StringBuffer bodyBuffer = new StringBuffer(mailBody); if (!kibanaUrls.isEmpty()) { bodyBuffer.append("\n\n"); } // Add urls info to e-mail for (Map<String, String> kibanaUrl : kibanaUrls) { // Add urls to e-mail String urlName = kibanaUrl.get(NAME_KEY); String reportUrl = kibanaUrl.get(URL_KEY); if (urlName != null && reportUrl != null) { bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n"); } } // Fill the message messageBodyPart.setText(bodyBuffer.toString()); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachments for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) { messageBodyPart = new MimeBodyPart(); String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY); String filename = kibanaScreenCapture.get(FILE_NAME_KEY); DataSource source = new FileDataSource(absoluteFilename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); logger.info("Sent mail message successfully"); } catch (MessagingException mex) { throw new RuntimeException(mex); } }
From source file:bo.com.offercruzmail.imp.FormadorMensajes.java
public static Multipart getMensajeUsuarioAyuda(boolean comandoReconocido) throws MessagingException { Multipart multiPartes = new MimeMultipart(); StringBuilder mensaje = new StringBuilder(); if (comandoReconocido) { //Es ayuda mensaje.append("Manual de comandos para el sistema de lector de bandeja Kibo. <br /><br />"); } else {/*from w w w.j av a2 s . c o m*/ mensaje.append(escapeHtml4( "El mensaje no ha sido reconocido, consulte el manual para enviar un mensaje vlido.")); mensaje.append("<br /><br />"); } mensaje.append(FormadorMensajes.tablaHtmlAyuda); multiPartes.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(mensaje.toString())); return multiPartes; }
From source file:org.latticesoft.util.resource.MessageUtil.java
/** * Sends the email./*ww w .jav a 2 s .com*/ * @param info the EmailInfo containing the message and other details * @param p the properties to set in the environment when instantiating the session * @param auth the authenticator */ public static void sendMail(EmailInfo info, Properties p, Authenticator auth) { try { if (p == null) { if (log.isErrorEnabled()) { log.error("Null properties!"); } return; } Session session = Session.getInstance(p, auth); session.setDebug(true); if (log.isInfoEnabled()) { log.info(p); log.info(session); } MimeMessage mimeMessage = new MimeMessage(session); if (log.isInfoEnabled()) { log.info(mimeMessage); log.info(info.getFromAddress()); } mimeMessage.setFrom(info.getFromAddress()); mimeMessage.setSentDate(new Date()); List l = info.getToList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); if (log.isInfoEnabled()) { log.info(addr); } mimeMessage.addRecipients(Message.RecipientType.TO, addr); } } l = info.getCcList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.CC, addr); } } l = info.getBccList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.BCC, addr); } } if (info.getAttachment().size() == 0) { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); mimeMessage.setText(info.getContent(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); mimeMessage.setText(info.getContent()); } mimeMessage.setContent(info.getContent(), info.getContentType()); } else { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); } Multipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); if (info.getCharSet() != null) { body.setText(info.getContent(), info.getCharSet()); body.setContent(info.getContent(), info.getContentType()); } else { body.setText(info.getContent()); body.setContent(info.getContent(), info.getContentType()); } mp.addBodyPart(body); for (int i = 0; i < info.getAttachment().size(); i++) { String filename = (String) info.getAttachment().get(i); MimeBodyPart attachment = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); attachment.setDataHandler(new DataHandler(fds)); attachment.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachment); } mimeMessage.setContent(mp); } Transport.send(mimeMessage); } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Error in sending email", e); } } }
From source file:com.email.SendEmailCalInvite.java
/** * Sends email based off of the section it comes from. This creates a * calendar invite object that is interactive by Outlook. * * @param eml EmailOutInviteModel//w w w . j a v a 2 s . c o m */ public static void sendCalendarInvite(EmailOutInvitesModel eml) { SystemEmailModel account = null; //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(eml.getSection())) { account = acc; break; } } if (account != null) { //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getToAddress() == null) ? "".split(";") : eml.getToAddress().split(";")); String[] CCAddressess = ((eml.getCcAddress() == null) ? "".split(";") : eml.getCcAddress().split(";")); String emailSubject = ""; BodyPart emailBody = body(eml); BodyPart inviteBody = null; if (eml.getHearingRoomAbv() == null) { emailSubject = eml.getEmailSubject() == null ? (eml.getEmailBody() == null ? eml.getCaseNumber() : eml.getEmailBody()) : eml.getEmailSubject(); inviteBody = responseDueCalObject(eml, account); } else { emailSubject = eml.getEmailSubject() == null ? Subject(eml) : eml.getEmailSubject(); inviteBody = inviteCalObject(eml, account, emailSubject); } //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart("alternative"); try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String Cc : CCAddressess) { if (EmailValidator.getInstance().isValid(Cc)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(Cc)); } } smessage.setSubject(emailSubject); multipart.addBodyPart(emailBody); multipart.addBodyPart(inviteBody); smessage.setContent(multipart); if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Cal Invite Not Actually Sent: " + eml.getId() + " - " + emailSubject); } EmailOutInvites.deleteEmailEntry(eml.getId()); } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } }
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//from w ww.j av a 2s . c o 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:bo.com.offercruzmail.imp.FormadorMensajes.java
public static Multipart enviarErroresNegocio(BusinessException errores) throws MessagingException { Multipart cuerpo = new MimeMultipart(); StringBuilder mensaje = new StringBuilder(); if (errores instanceof PermisosInsuficientesException) { mensaje.append(errores.getMessage()); } else {//from w w w.j ava 2s . co m mensaje.append(escapeHtml4("No se pudo completar la peticin debido a los siguiente errores:")); mensaje.append("<br /><br />"); StringBuilder filas = new StringBuilder(); for (BusinessExceptionMessage error : errores.getMessages()) { if (error.getIndex() > 0) { filas.append(FormadorMensajes.envolverFilaExcepcion(error.getIndex() + "", escapeHtml4(error.getMessage()))); } else { filas.append(FormadorMensajes.envolverFilaExcepcion("-", escapeHtml4(error.getMessage()))); } } mensaje.append(FormadorMensajes.envolverTablaExcepcion(filas.toString())); } cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(mensaje.toString())); return cuerpo; }