List of usage examples for javax.mail Message setSubject
public abstract void setSubject(String subject) throws MessagingException;
From source file:org.apache.jmeter.reporters.MailerModel.java
/** * Sends a mail with the given parameters using SMTP. * * @param from// w w w. ja v a 2 s.c o m * the sender of the mail as shown in the mail-client. * @param vEmails * all receivers of the mail. The receivers are seperated by * commas. * @param subject * the subject of the mail. * @param attText * the message-body. * @param smtpHost * the smtp-server used to send the mail. * @param smtpPort the smtp-server port used to send the mail. * @param user the login used to authenticate * @param password the password used to authenticate * @param mailAuthType {@link MailAuthType} Security policy * @param debug Flag whether debug messages for the mail session should be generated * @throws AddressException If mail address is wrong * @throws MessagingException If building MimeMessage fails */ public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost, String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug) throws AddressException, MessagingException { InternetAddress[] address = new InternetAddress[vEmails.size()]; for (int k = 0; k < vEmails.size(); k++) { address[k] = new InternetAddress(vEmails.get(k)); } // create some properties and get the default Session Properties props = new Properties(); props.put(MAIL_SMTP_HOST, smtpHost); props.put(MAIL_SMTP_PORT, smtpPort); // property values are strings Authenticator authenticator = null; if (mailAuthType != MailAuthType.NONE) { props.put(MAIL_SMTP_AUTH, "true"); switch (mailAuthType) { case SSL: props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory"); break; case TLS: props.put(MAIL_SMTP_STARTTLS, "true"); break; default: break; } } if (!StringUtils.isEmpty(user)) { authenticator = new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }; } Session session = Session.getInstance(props, authenticator); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setText(attText); Transport.send(msg); }
From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java
/** Send mail in HTML format */ private boolean sendHtmlMail(MailSenderInfo mailInfo) { boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable"); if (enableMailAlert) { SaAuthenticatorInfo authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword()); }//from w w w . j av a2 s.c o m Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { Message mailMessage = new MimeMessage(sendMailSession); Address from = new InternetAddress(mailInfo.getFromAddress()); mailMessage.setFrom(from); Address[] to = new Address[mailInfo.getToAddress().split(",").length]; int i = 0; for (String e : mailInfo.getToAddress().split(",")) to[i++] = new InternetAddress(e); mailMessage.setRecipients(Message.RecipientType.TO, to); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8"); mainPart.addBodyPart(html); if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) { for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) { MimeBodyPart mbp = new MimeBodyPart(); File file = new File(entry.getValue()); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); try { mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null)); } catch (Exception e) { e.printStackTrace(); } mbp.setContentID(entry.getKey()); mbp.setHeader("Content-ID", "<image>"); mainPart.addBodyPart(mbp); } } List<File> list = mailInfo.getFileList(); if (list != null && list.size() > 0) { for (File f : list) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f.getAbsolutePath()); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(f.getName()); mainPart.addBodyPart(mbp); } list.clear(); } mailMessage.setContent(mainPart); // mailMessage.saveChanges(); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } } return false; }
From source file:Implement.Service.AdminServiceImpl.java
@Override public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException { String path = System.getProperty("catalina.base"); MimeBodyPart logo = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png")); logo.setDataHandler(new DataHandler(source)); logo.setFileName("logoIcon.png"); logo.setDisposition(MimeBodyPart.INLINE); logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid MimeBodyPart facebook = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png")); facebook.setDataHandler(new DataHandler(source)); facebook.setFileName("facebookIcon.png"); facebook.setDisposition(MimeBodyPart.INLINE); facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid MimeBodyPart twitter = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png")); twitter.setDataHandler(new DataHandler(source)); twitter.setFileName("twitterIcon.png"); twitter.setDisposition(MimeBodyPart.INLINE); twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid MimeBodyPart insta = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png")); insta.setDataHandler(new DataHandler(source)); insta.setFileName("instaIcon.png"); insta.setDisposition(MimeBodyPart.INLINE); insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid MimeBodyPart youtube = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png")); youtube.setDataHandler(new DataHandler(source)); youtube.setFileName("youtubeIcon.png"); youtube.setDisposition(MimeBodyPart.INLINE); youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid MimeBodyPart pinterest = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png")); pinterest.setDataHandler(new DataHandler(source)); pinterest.setFileName("pinterestIcon.png"); pinterest.setDisposition(MimeBodyPart.INLINE); pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid String content = "<div style=' width: 507px;background-color: #f2f2f4;'>" + " <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>" + " <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>" + " <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + " </div>" + " <div style=' padding: 50px;margin-bottom: 20px;'>" + " <div id='email-form'>" + " <div style='margin-bottom: 20px'>" + " Hi " + emailData.getLastName() + " ,<br/>" + " Your package " + emailData.getLastestPackageName() + " has been approved" + " </div>" + " <div style='margin-bottom: 20px'>" + " Thanks,<br/>" + " Youtripper team\n" + " </div>" + " </div>" + " <div style='border-top: solid 1px #c4c5cc;text-align:center;'>" + " <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>" + " <div>" + " <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>" + " <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>" + " <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>" + " <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>" + " <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>" + " </div>" + " <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon," + " <br>Pravet, Bangkok, Thailand 10250</p>" + " </div>" + " </div>" + "</div>"; MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1);/* w w w .j av a 2s.c o m*/ mp.addBodyPart(logo); mp.addBodyPart(facebook); mp.addBodyPart(twitter); mp.addBodyPart(insta); mp.addBodyPart(youtube); mp.addBodyPart(pinterest); final String username = "noreply@youtripper.com"; final String password = "Tripper190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("noreply@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail())); message.setSubject("Package Approved!"); message.setContent(mp); message.saveChanges(); Transport.send(message); return true; }
From source file:org.webguitoolkit.messagebox.mail.MailChannel.java
@Override public void send(IMessage message) { try {// ww w . j a v a 2 s.c o m Message mail = new MimeMessage(getSession()); mail.addFrom(new InternetAddress[] { new InternetAddress(message.getSender()) }); Set<String> recipients = message.getRecipients(); if (recipients.isEmpty()) return; for (String recipient : recipients) { mail.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } mail.setSubject(message.getSubject()); mail.setContent(message.getBody(), message.getContentType()); Transport.send(mail); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.sfs.ucm.service.MailService.java
/** * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager. * //w w w . ja v a2 s .c o m * @param fromAddress * @param ccRe * @param toRecipient * @param subject * @param body * @param messageType * - text/plain or text/html * @return status message * @throws IllegalArgumentException */ @Asynchronous public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient, final String subject, final String body, final String messageType) throws IllegalArgumentException { // argument validation if (fromAddress == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress"); } if (toRecipient == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient"); } if (subject == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined subject"); } if (body == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent"); } if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) { throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType"); } String status = null; try { Properties props = new Properties(); props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host")); props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port")); Object[] params = new Object[4]; params[0] = (String) subject; params[1] = (String) fromAddress; params[2] = (String) ccRecipient; params[3] = (String) toRecipient; logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params); Session session = Session.getDefaultInstance(props); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); Address toAddress = new InternetAddress(toRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); if (StringUtils.isNotBlank(ccRecipient)) { Address ccAddress = new InternetAddress(ccRecipient); message.addRecipient(Message.RecipientType.CC, ccAddress); } message.setSubject(subject); message.setContent(body, messageType); Transport.send(message); } catch (AddressException e) { logger.error("sendMessage Address Exception occurred: {}", e.getMessage()); status = "sendMessage Address Exception occurred"; } catch (MessagingException e) { logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage()); status = "sendMessage Messaging Exception occurred"; } return new AsyncResult<String>(status); }
From source file:net.kamhon.ieagle.function.email.SendMail.java
public void send(String to, String cc, String bcc, String from, String subject, String text, String emailType) { // Session session = Session.getInstance(props, null); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailServerSetting.getUsername(), emailServerSetting.getPassword()); }//from w ww . j a v a 2s . c o m }); session.setDebug(emailServerSetting.isDebug()); try { Message msg = new MimeMessage(session); if (StringUtils.isNotBlank(from)) { msg.setFrom(new InternetAddress(from)); } else { msg.setFrom(); } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (StringUtils.isNotBlank(cc)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if (StringUtils.isNotBlank(bcc)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } msg.setSubject(subject); if (Emailq.TYPE_HTML.equalsIgnoreCase(emailType)) { msg.setContent(text, "text/html"); } else { msg.setText(text); } msg.setSentDate(new java.util.Date()); Transport.send(msg); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); } throw new SystemErrorException(mex); } }
From source file:common.email.MailServiceImpl.java
/** * this method sends email using a given template * @param subject subject of a mail/* w w w . ja v a 2 s . c om*/ * @param recipientEmail email receiver adress * @param mail mail text to send * @param from will be set * @return true if send succeed * @throws java.io.FileNotFoundException * @throws java.io.IOException */ protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException { try { Properties props = new Properties(); //props.put("mailHost", mailHost); Session session = Session.getInstance(props); // construct the message javax.mail.Message msg = new javax.mail.internet.MimeMessage(session); if (from == null) { msg.setFrom(); } else { try { msg.setFrom(new InternetAddress(from)); } catch (MessagingException ex) { logger.error(ex); } } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); msg.setSubject(subject); msg.setSentDate(new Date()); //msg.setHeader("", user) msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8"))); SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); t.connect(mailHost, user, password); Address[] a = msg.getAllRecipients(); t.sendMessage(msg, a); t.close(); return true; } catch (MessagingException ex) { logger.error(ex); ex.printStackTrace(); return false; } }
From source file:de.egore911.opengate.services.PilotService.java
@POST @Path("/register") @Produces("application/json") @Documentation("Register a new pilot. This will at first verify the login and email are " + "unique and the email is valid. After this it will register the pilot and send " + "and email to him to verify the address. The 'verify' will finalize the registration. " + "This method returns a JSON object containing a status field, i.e. {status: 'failed', " + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal " + "error occured an HTTP 500 will be sent.") public Response performRegister(@FormParam("login") String login, @FormParam("email") String email, @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) { JSONObject jsonObject = new JSONObject(); EntityManager em = EntityManagerFilter.getEntityManager(); Number n = (Number) em .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)") .setParameter("login", login).getSingleResult(); if (n.intValue() > 0) { try {/*from www. j ava2s . c om*/ StatusHelper.failed(jsonObject, "Duplicate login"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)") .setParameter("email", email).getSingleResult(); if (n.intValue() > 0) { try { StatusHelper.failed(jsonObject, "Duplicate email"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } InternetAddress recipient; try { recipient = new InternetAddress(email, login); } catch (UnsupportedEncodingException e1) { try { StatusHelper.failed(jsonObject, "Invalid email"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } Faction faction; try { faction = em.find(Faction.class, factionId); } catch (NoResultException e) { try { StatusHelper.failed(jsonObject, "Invalid faction"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e1) { LOG.log(Level.SEVERE, e.getMessage(), e1); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } Vessel vessel; try { vessel = (Vessel) em .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction " + "order by vessel.techLevel asc") .setParameter("faction", faction).setMaxResults(1).getSingleResult(); // TODO assign initical equipment as well } catch (NoResultException e) { try { StatusHelper.failed(jsonObject, "Faction has no vessel"); return Response.ok(jsonObject.toString()).build(); } catch (JSONException e1) { LOG.log(Level.SEVERE, e.getMessage(), e1); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } String passwordHash; String password = randomText(); try { passwordHash = hashPassword(password); } catch (NoSuchAlgorithmException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } em.getTransaction().begin(); try { Pilot pilot = new Pilot(); pilot.setLogin(login); pilot.setCreated(new Date()); pilot.setPasswordHash(passwordHash); pilot.setEmail(email); pilot.setFaction(faction); pilot.setVessel(vessel); pilot.setVerificationCode(randomText()); em.persist(pilot); em.getTransaction().commit(); try { // send e-mail to registered user containing the new password Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user " + pilot.getLogin() + " with your e-mail adress. The following credentials can be used for your account:\n" + " login : " + pilot.getLogin() + "\n" + " password : " + password + "\n\n" + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/" + pilot.getLogin() + "?verification=" + pilot.getVerificationCode(); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration")); msg.addRecipient(Message.RecipientType.TO, recipient); msg.setSubject("Your Example.com account has been activated"); msg.setText(msgBody); Transport.send(msg); } catch (AddressException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } catch (MessagingException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } catch (UnsupportedEncodingException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } StatusHelper.ok(jsonObject); jsonObject.put("id", pilot.getKey().getId()); jsonObject.put("vessel_id", pilot.getVessel().getKey().getId()); // TODO properly wrap the vessel and its equipment/cargo return Response.ok(jsonObject.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } catch (NoResultException e) { return Response.status(Status.FORBIDDEN).build(); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } } }
From source file:Model.DAO.java
public void sendEmail(int id, String status) { SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm"); Properties props = new Properties(); /** Parmetros de conexo com servidor Gmail */ props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("seuemail@gmail.com", "suasenha"); }/*from ww w.j a va2 s .com*/ }); /** Ativa Debug para sesso */ try { PreparedStatement stmt = this.conn .prepareStatement("SELECT * FROM Reservation re WHERE idReservas = ?"); stmt.setInt(1, id); ResultSet rs = stmt.executeQuery(); rs.next(); String date = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[0]; String time = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[1]; Message message = new MimeMessage(session); message.setFrom(new InternetAddress("pck1993@gmail.com")); //Remetente Address[] toUser = InternetAddress //Destinatrio(s) .parse(rs.getString("email")); message.setRecipients(Message.RecipientType.TO, toUser); message.setSubject("Status Reserva");//Assunto message.setText("Email de alterao do status da resreva no dia " + date + " s " + time + " horas para " + status); /**Mtodo para enviar a mensagem criada*/ Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java
protected void fillSubject(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String subject = getTemplate().getSubject(); if (subject != null) { try {/*from w ww. j av a 2s. co m*/ String evaluatedSubject = evaluateExpression(execution, subject, session).replaceAll("[\r\n]", ""); email.setSubject(WordUtils.abbreviate(evaluatedSubject, 60, 74, "...")); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } } }