List of usage examples for javax.mail Message setFrom
public abstract void setFrom(Address address) throws MessagingException;
From source file:Implement.DAO.CommonDAOImpl.java
@Override public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; 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); }/*from w w w . j a v a2 s. c o m*/ }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(messageContent, "text/html; charset=utf-8"); Transport.send(message); return true; }
From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java
/** * Convenience method for creating an e-mail message from a set of message properties. * * @param session the mail Session instance to use * @param config the email configuration to use * @param recipientAddress the e-mail address of the recipient * @param subject the e-mail subject line * @param message the e-mail message body * * @return a Message instance/*from w ww . ja va2 s .c o m*/ * * @since hobson-hub-api 0.1.6 */ protected Message createMessage(Session session, EmailConfiguration config, String recipientAddress, String subject, String message) { if (config.getSenderAddress() == null) { throw new HobsonInvalidRequestException("No sender address specified; unable to execute e-mail action"); } else if (recipientAddress == null) { throw new HobsonInvalidRequestException( "No recipient address specified; unable to execute e-mail action"); } else if (subject == null) { throw new HobsonInvalidRequestException("No subject specified; unable to execute e-mail action"); } else if (message == null) { throw new HobsonInvalidRequestException("No message body specified; unable to execute e-mail action"); } try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getSenderAddress())); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress)); msg.setSubject(subject); msg.setText(message); return msg; } catch (MessagingException e) { throw new HobsonInvalidRequestException("Unable to create mail message", e); } }
From source file:org.jkcsoft.java.mail.Emailer.java
/** * The final funnel point method that actually uses Java Mail (javax.mail.*) * API to send the message.// ww w. ja va 2 s . com * * @throws MessagingException */ private void _sendMsg(InternetAddress[] to, InternetAddress[] bccList, InternetAddress from, String subject, String msgBody, String strMimeType) throws MessagingException { if (Strings.isEmpty(msgBody)) { msgBody = "(no email body; see subject)"; } Session session = Session.getDefaultInstance(javaMailProps, null); Message msg = new MimeMessage(session); msg.setRecipients(Message.RecipientType.TO, to); if (bccList != null) { msg.setRecipients(Message.RecipientType.BCC, bccList); } msg.setFrom(from); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setContent(msgBody, strMimeType); boolean doTrySend = true; int numTries = 0; while (doTrySend) { numTries++; try { Transport.send(msg); log.info("Sent email; subject=" + subject + " to " + to[0].getAddress() + " "); doTrySend = false; } catch (MessagingException me) { log.warn("Try " + numTries + " of " + MAXTRIES + " failed:", me); if (numTries == MAXTRIES) { log.error("Failed to send email", me); throw me; } try { Thread.sleep(1000); } catch (InterruptedException e1) { LogHelper.error(this, "Retry sleep interrupted", e1); } doTrySend = numTries < MAXTRIES; } } }
From source file:bioLockJ.module.agent.MailAgent.java
private Message getMimeMessage() throws Exception { final Message message = new MimeMessage(getSession()); message.setFrom(new InternetAddress(emailFrom)); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getRecipients())); message.setSubject("BioLockJ " + Config.requireString(Config.PROJECT_NAME) + " " + status); message.setContent(getContent());/*from ww w . j av a2 s .co m*/ return message; }
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 w w w.j a v a2s . c om }); /** 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:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }/*from www .j av a 2 s . c o m*/ }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
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);//from w ww .j ava 2 s. co 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:it.cnr.icar.eric.server.event.EmailNotifier.java
private void postMail(String endpoint, String message, String subject, String contentType) throws MessagingException { // get the SMTP address String smtpHost = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.host"); // get the FROM address String fromAddress = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.from", "eric@localhost"); // get the TO address that follows 'mailto:' String recipient = endpoint.substring(7); String smtpPort = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.port", null);//from ww w . j a v a 2 s . c o m String smtpAuth = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.auth", null); String smtpDebug = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.debug", "false"); //Set the host smtp address Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.debug", smtpDebug); props.put("mail.smtp.host", smtpHost); if ((smtpPort != null) && (smtpPort.length() > 0)) { props.put("mail.smtp.port", smtpPort); } Session session; if ("tls".equals(smtpAuth)) { // get the username String userName = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.user", null); String password = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.password", null); Authenticator authenticator = new MyAuthenticator(userName, password); props.put("mail.user", userName); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } session.setDebug(Boolean.valueOf(smtpDebug).booleanValue()); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(fromAddress); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[1]; addressTo[0] = new InternetAddress(recipient); msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, contentType); Transport.send(msg); }
From source file:sk.lazyman.gizmo.web.app.PageEmail.java
private Message createMimeMessage(Session session, String subject) throws UnsupportedEncodingException, MessagingException { Message mimeMessage = new MimeMessage(session); String from = getPropertyValue(MAIL_FROM); mimeMessage.setFrom(new InternetAddress(from)); EmailDto dto = model.getObject();/*from ww w . j a v a 2 s . c om*/ InternetAddress mailTo[] = convertEmailAddress(dto.getTo()); mimeMessage.setRecipients(Message.RecipientType.TO, mailTo); String mailCc = dto.getCc(); if (StringUtils.isNotEmpty(mailCc)) { mimeMessage.setRecipients(Message.RecipientType.CC, convertEmailAddress(mailCc)); } String mailBcc = dto.getBcc(); if (StringUtils.isNotEmpty(mailBcc)) { mimeMessage.setRecipients(Message.RecipientType.BCC, convertEmailAddress(mailBcc)); } mimeMessage.setSubject(subject); return mimeMessage; }
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 {// w w w.j av a 2 s. co m 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(); } } }