List of usage examples for javax.mail.internet MimeMessage setSubject
@Override public void setSubject(String subject) throws MessagingException
From source file:com.azprogrammer.qgf.controllers.HomeController.java
@RequestMapping(value = "/wbmail") public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) { model.clear();//ww w. j av a2 s . c o m try { WBEmail email = new WBEmail(); HttpSession session = req.getSession(); String userName = session.getAttribute("userName").toString(); String toAddress = req.getParameter("email"); if (!WebUtil.isValidEmail(toAddress)) { throw new Exception("invalid email"); } //TODO validate message contents email.setFromUser(userName); email.setToAddress(toAddress); WhiteBoard wb = getWhiteBoard(req); if (wb == null) { throw new Exception("Invalid White Board"); } email.setWbKey(wb.getKey()); email.setCreationTime(System.currentTimeMillis()); Properties props = new Properties(); Session mailsession = Session.getDefaultInstance(props, null); String emailError = null; try { MimeMessage msg = new MimeMessage(mailsession); msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); msg.setSubject("Please join the whiteboard session on " + req.getServerName()); String msgBody = "To join " + userName + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "</a>"; msg.setText(msgBody, "UTF-8", "html"); Transport.send(msg); } catch (AddressException e) { emailError = e.getMessage(); } catch (MessagingException e) { emailError = e.getMessage(); } if (emailError == null) { email.setStatus(WBEmail.STATUS_SENT); } else { email.setStatus(WBEmail.STATUS_ERROR); } getPM().makePersistent(email); if (email.getStatus() == WBEmail.STATUS_ERROR) { throw new Exception(emailError); } model.put("status", "ok"); } catch (Exception e) { model.put("error", e.getMessage()); } return doJSON(model); }
From source file:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java
/** @see NotificationStrategy#execute(NotificationAddress[], Message) */ public final void execute(final NotificationAddress[] addresses, final Message message) { try {/*from ww w . j a v a 2 s . c o m*/ final MailSender mailSender = getMailSender(); //This is ugly....but if it is not a JavaMailSender it will //fail (for instance during tests). And the only way to //create a Multipartemail is through JavaMailSender if (mailSender instanceof JavaMailSender) { final JavaMailSender javaMailSender = (JavaMailSender) mailSender; final MimeMessage mail = javaMailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(mail, true); helper.setFrom(getFromAddress().getEmailStr()); helper.setTo(SimpleEmailNotificationStrategy.getEmailAddresses(addresses)); helper.setReplyTo(getEmailAddress(message.getReplyToAddress())); helper.setSubject(message.getSubject()); setContent(helper, (MultipartMessage) message); addHeaders(message, mail); javaMailSender.send(mail); } else { final SimpleMailMessage mail = new SimpleMailMessage(); mail.setFrom(getFromAddress().getEmailStr()); mail.setTo(getEmailAddresses(addresses)); mail.setReplyTo(getEmailAddress(message.getReplyToAddress())); mail.setSubject(message.getSubject()); mail.setText(message.getContent()); mailSender.send(mail); } } catch (final MessagingException e) { throw new RuntimeException("Could not send message", e); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Could not send message", e); } }
From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }// w w w. ja v a 2 s .com if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(getPlainTextContent(), "text/plain"); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(getHtmlContent(), "text/html"); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); 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); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/* ww w . j a v a 2 s. c om*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:org.squale.squalecommon.util.mail.javamail.JavaMailProviderImpl.java
/** * This method send mail//from w ww. j ava 2 s .c o m * * @param sender Sender Address * @param recipients List of recipient address * @param subject Subject of the mail * @param content Content of the mail * @throws MailException Exception happened the send of the mail */ public void sendMail(String sender, String[] recipients, String subject, String content) throws MailException { // Initialization of the mail provider init(); // if there is mail configuration information if (smtpServer != null && (senderAddress != null || sender != null)) { // Properties used for sending mails Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); Session session = smtpAuthent(props); // Header message definition MimeMessage message = new MimeMessage(session); try { // If a sender argument is not null we use it if (sender != null) { message.setFrom(new InternetAddress(sender)); } // If the sender argument is null else { message.setFrom(new InternetAddress(senderAddress)); } // We send to each recipient for (int i = 0; i <= recipients.length - 1; i++) { String mailAddress = (String) recipients[i]; LOG.debug("Recipent : " + recipients[i]); message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mailAddress)); } // Body message definition message.setSubject(subject); message.setText(content, "iso-8859-1"); // Send of the mail Transport.send(message); } catch (AddressException e) { throw new MailException(e); } catch (MessagingException e) { throw new MailException(e); } } else { String message = MailMessages.getString("mail.exception.noConfig"); throw new MailException(message); } }
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"); }// ww w . ja v a 2 s. c om 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:eu.planets_project.pp.plato.action.session.ExceptionAction.java
@RaiseEvent("exceptionHandled") public String sendMail() { try {/*from w ww . j a v a 2s. c om*/ 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.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 . j ava2 s . c o 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:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java
private Result sendMail(MCPackageMail mcPackageMail) { try {/*from ww w .j a v a 2s. c om*/ Map<String, String> statusAction = new HashMap<>(); statusAction.put("NEW", "released"); statusAction.put("CANCEL", "withdrawn"); statusAction.put("UPDATE", "updated"); String html = mcPackageMail.getMail(); ArrayList<String> to = new ArrayList<>(); to.add(mcPackageMail.getDestination()); String from = mcPackageMail.getSource(); String host = Configuration.getInstance().getSmtpHost(); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.localhost", host); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (String s : to) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(s)); } System.out.println("Destination: " + Arrays.asList(to).toString()); message.setSubject(mcPackageMail.getSubject().replace("[", "").replace("]", "")); message.setContent(html, "text/html"); Transport.send(message); System.out.println("Release mail for " + mcPackageMail.getPackageName() + "-" + mcPackageMail.getPackageVersion() + " was succesfully sent!"); } catch (Exception ex) { Logger.getLogger(ProcessTCRequest.class.getName()).log(Level.SEVERE, null, ex); result.setResultCode("1"); result.setResultMessage(ex.getMessage()); } return result; }
From source file:com.intranet.intr.proveedores.EmpControllerGestion.java
public void enviarProvUC(proveedores proveedor) { String cuerpo = ""; String servidorSMTP = "smtp.1and1.es"; String puertoEnvio = "465"; Properties props = new Properties();//propiedades a agragar props.put("mail.smtp.user", miCorreo);//correo origen props.put("mail.smtp.host", servidorSMTP);//tipo de servidor props.put("mail.smtp.port", puertoEnvio);//puesto de salida props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor props.put("mail.smtp.auth", "true");//autentificacion props.put("mail.smtp.password", "angel2010");//autentificacion props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); SecurityManager security = System.getSecurityManager(); Authenticator auth = new autentificadorSMTP();//autentificar el correo Session session = Session.getInstance(props, auth);//se inica una session // session.setDebug(true); try {/* w ww . j a va 2 s . c o m*/ // Creamos un objeto mensaje tipo MimeMessage por defecto. MimeMessage mensajeE = new MimeMessage(session); // Asignamos el de o from? al header del correo. mensajeE.setFrom(new InternetAddress(miCorreo)); // Asignamos el para o to? al header del correo. mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail())); // Asignamos el asunto mensajeE.setSubject("Su Perfil Personal"); // Creamos un cuerpo del correo con ayuda de la clase BodyPart //BodyPart cuerpoMensaje = new MimeBodyPart(); // Asignamos el texto del correo String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: " + proveedor.getContrasenna() + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm"; // Asignamos el texto del correo cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>" + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>" + "</html>"; mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>" + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>" + "</html>", "text/html"); //mensaje.setText(text); // Creamos un multipart al correo // Enviamos el correo Transport.send(mensajeE); System.out.println("Mensaje enviado"); } catch (MessagingException e) { e.printStackTrace(); } }