List of usage examples for javax.mail BodyPart setText
public void setText(String text) throws MessagingException;
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText); multipart.addBodyPart(part);/*from w w w .j ava 2 s. c o m*/ // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:org.jresponder.message.MessageRefImpl.java
/** * Render a message in the context of a particular subscriber * and subscription./* ww w . j a va2 s . c o m*/ */ @Override public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber, Subscription aSubscription) { try { // prepare context Map<String, Object> myRenderContext = new HashMap<String, Object>(); myRenderContext.put("subscriber", aSubscriber); myRenderContext.put("subscription", aSubscription); myRenderContext.put("config", aSendConfig); myRenderContext.put("message", this); // render the whole file String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext); // now parse again with Jsoup Document myDocument = Jsoup.parse(myRenderedFileContents); String myHtmlBody = ""; String myTextBody = ""; // html body Elements myBodyElements = myDocument.select("#htmlbody"); if (!myBodyElements.isEmpty()) { myHtmlBody = myBodyElements.html(); } // text body Elements myJrTextBodyElements = myDocument.select("#textbody"); if (!myJrTextBodyElements.isEmpty()) { myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first()); } // now build the actual message MimeMessage myMimeMessage = aMimeMessage; // wrap it in a MimeMessageHelper - since some things are easier with that MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage); // set headers // subject myMimeMessageHelper.setSubject(TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext)); // TODO: implement DKIM, figure out subetha String mySenderEmailPattern = aSendConfig.getSenderEmailPattern(); String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext); myMimeMessage.setSender(new InternetAddress(mySenderEmail)); myMimeMessageHelper.setTo(aSubscriber.getEmail()); // from myMimeMessageHelper.setFrom( TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext), TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext)); // see how to set body // if we have both text and html, then do multipart if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) { // create wrapper multipart/alternative part MimeMultipart ma = new MimeMultipart("alternative"); myMimeMessage.setContent(ma); // create the plain text BodyPart plainText = new MimeBodyPart(); plainText.setText(myTextBody); ma.addBodyPart(plainText); // create the html part BodyPart html = new MimeBodyPart(); html.setContent(myHtmlBody, "text/html"); ma.addBodyPart(html); } // if only HTML, then just use that else if (myHtmlBody.trim().length() > 0) { myMimeMessageHelper.setText(myHtmlBody, true); } // if only text, then just use that else if (myTextBody.trim().length() > 0) { myMimeMessageHelper.setText(myTextBody, false); } // if neither text nor HTML, then the message is being skipped, // so we just return null else { return false; } return true; } catch (MessagingException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException { Properties props = new Properties(); //props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.host", emailHost); if (emailUser != null) { props.setProperty("mail.smtp.auth", "true"); }//from www . ja v a2 s . com Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass); Session mailSession = Session.getDefaultInstance(props, emailAuthenticator); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); // transport.connect(emailHost, emailUser, emailPass); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:net.sf.jclal.util.mail.SenderEmail.java
/** * Send the email with the indicated parameters * * @param subject The subject/* w ww. j a va 2 s. com*/ * @param content The content * @param reportFile The reportFile to send */ public void sendEmail(String subject, String content, File reportFile) { // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); if (!user.isEmpty() && !pass.isEmpty()) { properties.setProperty("mail.user", user); properties.setProperty("mail.password", pass); } // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, toRecipients.toString()); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(content); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); if (attachReporFile) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile))); messageBodyPart.setFileName(reportFile.getName()); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e); } }
From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java
@Override public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text, final Message previousMailMessage) { LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)"); if (suppressMail) { return;/*w w w. j a va 2s . c om*/ } setMailProperties(); MimeMessagePreparator messagePreparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) { setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses()); } if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) { setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses()); } if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) { setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses()); } if (null != mailMetaData.getFromAddress()) { mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName()) .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress()) .append(MailConstants.GREATER_SYMBOL).toString())); } if (null != mailMetaData.getSubject() && null != text) { mimeMessage.setSubject(mailMetaData.getSubject()); } if (null != text) { mimeMessage.setText(text); } // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE)); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(previousMailMessage.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message mimeMessage.setContent(multipart); } }; try { mailSender.send(messagePreparator); } catch (MailException mailException) { LOGGER.error("Error while sending mail to configured mail account", mailException); throw new SendMailException( EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException); } LOGGER.info("mail sent successfully"); }
From source file:com.ilopez.jasperemail.JasperEmail.java
public void emailReport(String emailHost, final String emailUser, final String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames, Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException { Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport); Properties props = new Properties(); // Setup Email Settings props.setProperty("mail.smtp.host", emailHost); props.setProperty("mail.smtp.port", smtpport.toString()); props.setProperty("mail.smtp.auth", smtpauth.toString()); if (smtpenc == OptionValues.SMTPType.SSL) { // SSL settings props.put("mail.smtp.socketFactory.port", smtpport.toString()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (smtpenc == OptionValues.SMTPType.TLS) { // TLS Settings props.put("mail.smtp.starttls.enable", "true"); } else {//from w w w .j av a 2 s .c o m // Plain } // Setup and Apply the Email Authentication Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailUser, emailPass); } }); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:bioLockJ.module.agent.MailAgent.java
private Multipart getContent() throws Exception { final Multipart multipart = new MimeMultipart(); final BodyPart messageBodyPart = new MimeBodyPart(); final List<BodyPart> attachments = getAttachments(); messageBodyPart.setText(getSummary()); multipart.addBodyPart(messageBodyPart); for (final BodyPart bp : attachments) { multipart.addBodyPart(bp);//w w w . ja v a2 s . c o m } return multipart; }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }// www . ja va 2 s . com if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from w w w . ja va 2 s.co m props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:checkwebsite.Mainframe.java
/** * * @param email/* ww w.ja v a 2 s . c o m*/ * @param msg */ protected void notify(String email, String msg) { // Recipient's email ID needs to be mentioned. String to = email;//change accordingly // go to link below and turn on Access for less secure apps //https://www.google.com/settings/security/lesssecureapps // Sender's email ID needs to be mentioned String from = "";//Enter your email id here final String username = "";//Enter your email id here final String password = "";//Enter your password here // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Report of your website : " + wurl); // // Now set the actual message // message.setText("Hello, " + msg + " this is sample for to check send " // + "email using JavaMailAPI "); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Now set the actual message messageBodyPart.setText("Please! find your website report in attachment"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = "WebsiteReport.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); lblWarning.setText("report sent..."); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }