List of usage examples for javax.mail.internet MimeMessage setText
@Override public void setText(String text) throws MessagingException
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail * /*from w w w . j av a 2 s . co m*/ * @param mail The original Mail object * @param session Mail session * @return The MIME message */ private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context) throws MessagingException, XWikiException, IOException { // this will also check for email error InternetAddress from = new InternetAddress(mail.getFrom()); String recipients = mail.getHeader("To"); if (StringUtils.isBlank(recipients)) { recipients = mail.getTo(); } else { recipients = mail.getTo() + "," + recipients; } InternetAddress[] to = toInternetAddresses(recipients); recipients = mail.getHeader("Cc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getCc(); } else { recipients = mail.getCc() + "," + recipients; } InternetAddress[] cc = toInternetAddresses(recipients); recipients = mail.getHeader("Bcc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getBcc(); } else { recipients = mail.getBcc() + "," + recipients; } InternetAddress[] bcc = toInternetAddresses(recipients); if ((to == null) && (cc == null) && (bcc == null)) { LOGGER.info("No recipient -> skipping this email"); return null; } MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setFrom(from); if (to != null) { message.setRecipients(javax.mail.Message.RecipientType.TO, to); } if (cc != null) { message.setRecipients(javax.mail.Message.RecipientType.CC, cc); } if (bcc != null) { message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc); } message.setSubject(mail.getSubject(), EMAIL_ENCODING); for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) { message.setHeader(header.getKey(), header.getValue()); } if (mail.getHtmlPart() != null || mail.getAttachments() != null) { Multipart multipart = createMimeMultipart(mail, context); message.setContent(multipart); } else { message.setText(mail.getTextPart()); } message.setSentDate(new Date()); message.saveChanges(); return message; }
From source file:eu.planets_project.pp.plato.action.session.ExceptionAction.java
@RaiseEvent("exceptionHandled") public String sendMail() { try {/*w w w .jav a 2 s . c o m*/ log.debug(body); Properties props = System.getProperties(); Properties mailProps = new Properties(); mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties")); props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(mailProps.getProperty("FROM"))); message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO"))); String exceptionType = "Unknown"; String exceptionMessage = ""; String stackTrace = ""; String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName(); if (lastHandledException != null) { exceptionType = lastHandledException.getClass().getCanonicalName(); exceptionMessage = lastHandledException.getMessage(); StringWriter writer = new StringWriter(); lastHandledException.printStackTrace(new PrintWriter(writer)); stackTrace = writer.toString(); } message.setSubject("[PlatoError] " + exceptionType + " at " + host); StringBuilder builder = new StringBuilder(); builder.append("Date: " + format.format(new Date()) + "\n"); builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n"); builder.append("ExceptionType: " + exceptionType + "\n"); builder.append("ExceptionMessage: " + exceptionMessage + "\n\n"); builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n"); builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n"); builder.append(stackTrace); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); this.lastHandledException = null; facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.", "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.")); } catch (Exception e) { log.debug(e.getMessage(), e); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bugreport couldn't be sent", "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. " + "Please send an email to plato@ifs.tuwien.ac.at with a " + "description of what you have been doing at the time of the error." + "Thank you very much!")); return null; } return "home"; }
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 . ja v a 2 s. 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:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * /* w w w . j a v a 2 s .co m*/ * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Hello, \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n\n"); builder.append( "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://" + serverString + "/idp/addUser.jsf.\n"); builder.append( "If you have an account, please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (MessagingException e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java
public void sendEmail(String subject, String text, String toEmail) { // Recipient's email ID needs to be mentioned. String to = toEmail;//from www. j a va 2s .co m // Sender's email ID needs to be mentioned String from = "flimplatereader@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties // Properties properties = System.getProperties(); Properties properties = System.getProperties(); // Setup mail server //properties.setProperty("mail.smtp.host", "10.101.3.229"); properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.setProperty("mail.user", "flimplatereader"); properties.setProperty("mail.password", "flimimages"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); //enable authentication final String pww = "flimimages"; Session session; session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication("flimplatereader@gmail.com", pww); } }); 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.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Now set the actual message message.setText(text); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom, String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost String host = ConfigManager.getInstance().getSmtpMailhost(); String port = ConfigManager.getInstance().getSmtpMailport(); String password = ConfigManager.getInstance().getSmtpMailpassword(); String auth = ConfigManager.getInstance().getSmtpMailauth(); String sender = ConfigManager.getInstance().getSmtpMailuser(); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.user", sender); properties.setProperty("mail.smtp.password", password); properties.setProperty("mail.smtp.auth", auth); properties.setProperty("mail.smtp.port", port); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. if (!StringUtils.isBlank(sender)) { try {/*from w w w.java2 s. c o m*/ message.setFrom(new InternetAddress(sender)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex); } } List<Address> addresses = new ArrayList<Address>(); String receivers = emails.getReceivers(); receivers = StringUtils.trim(receivers); for (String receiver : receivers.split(";")) { if (!StringUtils.isBlank(receiver)) { try { addresses.add(new InternetAddress(receiver)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex); } } } Address[] add = new Address[addresses.size()]; addresses.toArray(add); try { message.addRecipients(Message.RecipientType.TO, add); // Set Subject: header field message.setSubject("[Pundit Contact Form]: " + subject); // Now set the actual message message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n" + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex); } // Send message try { logger.log(Level.INFO, "Trying to send message to receivers: {0}", Arrays.toString(message.getAllRecipients())); transport = session.getTransport("smtp"); transport.connect(host, sender, password); transport.sendMessage(message, message.getAllRecipients()); logger.log(Level.INFO, "Sent messages to all receivers {0}", Arrays.toString(message.getAllRecipients())); } catch (NoSuchProviderException nspe) { logger.log(Level.SEVERE, "Cannot find smtp provider", nspe); } catch (MessagingException me) { logger.log(Level.SEVERE, "Cannot set transport layer ", me); } finally { try { transport.close(); } catch (MessagingException ex) { } catch (NullPointerException ne) { } } }
From source file:org.cern.flume.sink.mail.MailSink.java
@Override public Status process() throws EventDeliveryException { Status status = null;/*from w w w .j a v a2 s.co m*/ // Start transaction Channel ch = getChannel(); Transaction txn = ch.getTransaction(); txn.begin(); try { Event event = ch.take(); if (event != null) { // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage mimeMessage = new MimeMessage(session); // Set From: header field of the header. mimeMessage.setFrom(new InternetAddress(sender)); // Set To: header field of the header. for (String recipient : recipients) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } // Now set the subject and actual message Map<String, String> headers = event.getHeaders(); String value; String mailSubject = subject; for (String field : subjectFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailSubject = mailSubject.replace("%{" + field + "}", value); } String mailMessage = message; for (String field : messageFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailMessage = mailMessage.replace("%{" + field + "}", value); } mimeMessage.setSubject(mailSubject); mimeMessage.setText(mailMessage); // Send message Transport.send(mimeMessage); } txn.commit(); status = Status.READY; } catch (Throwable t) { txn.rollback(); logger.error("Unable to send e-mail.", t); status = Status.BACKOFF; if (t instanceof Error) { throw (Error) t; } } finally { txn.close(); } return status; }
From source file:eu.scape_project.planning.application.BugReport.java
/** * Method responsible for sending a bug report per mail. * //from w ww. j av a 2 s. c o m * @param userEmail * email address of the user. * @param errorDescription * error description given by the user. * @param exception * the exception causing the bug/error. * @param requestUri * request URI where the error occurred * @param location * the location of the application where the error occurred * @param applicationName * application name * @param plan * the plan where the exception occurred * @throws MailException * if the bug report could not be sent */ public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri, String location, String applicationName, Plan plan) throws MailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback"))); message.setSubject("[" + applicationName + "] from " + location); StringBuilder builder = new StringBuilder(); // Date builder.append("Date: ").append(DATE_FORMAT.format(new Date())).append("\n\n"); // User info if (user == null) { builder.append("No user available.\n\n"); } else { builder.append("User: ").append(user.getUsername()).append("\n"); if (user.getUserGroup() != null) { builder.append("Group: ").append(user.getUserGroup().getName()).append("\n"); } } builder.append("UserMail: ").append(userEmail).append("\n\n"); // Plan if (plan == null) { builder.append("No plan available.").append("\n\n"); } else { builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n"); builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n"); } // Description builder.append("Description:\n"); builder.append(SEPARATOR_LINE); builder.append(errorDescription).append("\n"); builder.append(SEPARATOR_LINE).append("\n"); // Request URI builder.append("Request URI: ").append(requestUri).append("\n\n"); // Exception if (exception == null) { builder.append("No exception available.").append("\n"); } else { builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n"); builder.append("Exception message: ").append(exception.getMessage()).append("\n"); StringWriter writer = new StringWriter(); exception.printStackTrace(new PrintWriter(writer)); builder.append("Stacktrace:\n"); builder.append(SEPARATOR_LINE); builder.append(writer.toString()); builder.append(SEPARATOR_LINE); } message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(), config.getString("mail.feedback")); String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."; Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO", userMessage, user); try { utx.begin(); em.persist(notification); utx.commit(); } catch (Exception e) { log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e); } } catch (MessagingException e) { throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to " + config.getString("mail.feedback"), e); } }
From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java
public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception { final String from = request.getFrom(); if (null == from) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from"); }/*from www .j ava2 s .co m*/ final String to = request.getTo(); if (null == to) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to"); } response.setSuccess(false); final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>(); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { log.debug("Build mime message"); addRecipients(mimeMessage, Message.RecipientType.TO, to); addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc()); addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc()); addReplyTo(mimeMessage, request.getReplyTo()); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setSubject(request.getSubject()); // mimeMessage.setText(request.getText()); List<String> attachments = request.getAttachmentUrls(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart mailBody = new MimeBodyPart(); mailBody.setText(request.getText()); mp.addBodyPart(mailBody); if (null != attachments && !attachments.isEmpty()) { for (String url : attachments) { log.debug("add mime part for {}", url); MimeBodyPart part = new MimeBodyPart(); String filename = url; int pos = filename.lastIndexOf('/'); if (pos >= 0) { filename = filename.substring(pos + 1); } pos = filename.indexOf('?'); if (pos >= 0) { filename = filename.substring(0, pos); } part.setFileName(filename); String fixedUrl = url; if (fixedUrl.startsWith("../")) { fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3); } fixedUrl = fixedUrl.replace(" ", "%20"); part.setDataHandler(new DataHandler(new URL(fixedUrl))); mp.addBodyPart(part); } } mimeMessage.setContent(mp); log.debug("message {}", mimeMessage); } }; try { if (request.isSendMail()) { mailSender.send(preparator); cleanAttachmentConnection(attachmentConnections); log.debug("mail sent"); } if (request.isSaveMail()) { MimeMessage mimeMessage = new MimeMessage((Session) null); preparator.prepare(mimeMessage); // overwrite multipart body as we don't need the attachments mimeMessage.setText(request.getText()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); // add document in referral Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS); List<InternalFeature> features = vectorLayerService.getFeatures( KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null, VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES); InternalFeature orgReferral = features.get(0); log.debug("Got referral {}", request.getReferralId()); InternalFeature referral = orgReferral.clone(); List<InternalFeature> newFeatures = new ArrayList<InternalFeature>(); newFeatures.add(referral); Map<String, Attribute> attributes = referral.getAttributes(); OneToManyAttribute orgComments = (OneToManyAttribute) attributes .get(KtunaxaConstant.ATTRIBUTE_COMMENTS); List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue()); AssociationValue emailAsComment = new AssociationValue(); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE, "Mail: " + request.getSubject()); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY, securitycontext.getUserName()); emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date()); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false); comments.add(emailAsComment); OneToManyAttribute newComments = new OneToManyAttribute(comments); attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments); log.debug("Going to add mail as comment to referral"); vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features, newFeatures); } response.setSuccess(true); } catch (MailException me) { log.error("Could not send e-mail", me); throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail"); } }