List of usage examples for javax.mail Message setFrom
public abstract void setFrom(Address address) throws MessagingException;
From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java
protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException { ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>(); // Setup fetchprofile to limit the stuff which is fetched FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE);//from w ww. j av a 2 s .c o m fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.CONTENT_INFO); fp.add(UIDFolder.FetchProfileItem.UID); folder.fetch(messages, fp); // loop over the fetched messages for (int i = 0; i < messages.length && i < offset; i++) { org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message(); Message m = messages[i]; String from = null; if (m.getFrom() != null && m.getFrom().length > 0) { from = MessageUtils.decodeText(m.getFrom()[0].toString()); } msg.setFrom(from); String replyto = null; if (m.getReplyTo() != null && m.getReplyTo().length > 0) { replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString()); } msg.setReplyto(replyto); ArrayList<String> to = new ArrayList<String>(); // Add to addresses Address[] toArray = m.getRecipients(RecipientType.TO); if (toArray != null) { for (Address addr : toArray) { String mailTo = MessageUtils.decodeText(addr.toString()); to.add(mailTo); } } msg.setTo(to); // Check if a subject exist and if so decode it String subject = m.getSubject(); if (subject != null) { subject = MessageUtils.decodeText(subject); } msg.setSubject(subject); // Add cc addresses Address[] ccArray = m.getRecipients(RecipientType.CC); ArrayList<String> cc = new ArrayList<String>(); if (ccArray != null) { for (Address addr : ccArray) { String mailCc = MessageUtils.decodeText(addr.toString()); cc.add(mailCc); } } msg.setCc(cc); userPreferences.addContact(from); userPreferences.addContact(to); userPreferences.addContact(replyto); userPreferences.addContact(cc); // Using sentDate since received date is not useful in the view when using fetchmail msg.setReceivedDate(m.getSentDate()); // Add flags ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags()); ArrayList<Tag> tags = new ArrayList<Tag>(); for (String flag : m.getFlags().getUserFlags()) { if (flag.startsWith(Tag.PREFIX)) { tags.add(new Tag(flag.substring(Tag.PREFIX.length()))); } } msg.setUid(folder.getUID(m)); msg.setFlags(iFlags); msg.setTags(tags); try { msg.setHasAttachments(hasAttachment(m)); } catch (MessagingException e) { logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:" + msg.getSubject() + " cause:" + e.getMessage()); logger.info(""); } mList.add(0, msg); } return mList; }
From source file:contestWebsite.Registration.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity contestInfo = Retrieve.contestInfo(); Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap()); for (Entry<String, String[]> param : params.entrySet()) { if (!"studentData".equals(param.getKey())) { params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) }); }//w w w. j a v a2s .c o m } String registrationType = params.get("registrationType")[0]; String account = "no"; if (params.containsKey("account")) { account = "yes"; } String email = params.containsKey("email") && params.get("email")[0].length() > 0 ? params.get("email")[0].toLowerCase().trim() : null; String schoolLevel = params.get("schoolLevel")[0]; String schoolName = params.get("schoolName")[0].trim(); String name = params.get("name")[0].trim(); String classification = params.containsKey("classification") ? params.get("classification")[0] : ""; String studentData = req.getParameter("studentData"); String password = null; String confPassword = null; UserCookie userCookie = UserCookie.getCookie(req); boolean loggedIn = userCookie != null && userCookie.authenticate(); if ((!loggedIn || !userCookie.isAdmin()) && email == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "E-Mail Address parameter ('email') must be specified"); return; } HttpSession sess = req.getSession(true); sess.setAttribute("registrationType", registrationType); sess.setAttribute("account", account); sess.setAttribute("account", account); sess.setAttribute("name", name); sess.setAttribute("classification", classification); sess.setAttribute("schoolName", schoolName); sess.setAttribute("schoolLevel", schoolLevel); sess.setAttribute("email", email); sess.setAttribute("studentData", studentData); boolean reCaptchaResponse = false; if (!(Boolean) sess.getAttribute("nocaptcha")) { URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s", URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset), URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset), URLEncoder.encode(req.getRemoteAddr(), charset)); final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection(); connection.setRequestProperty("Accept-Charset", charset); String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } }, Charsets.UTF_8)); try { JSONObject JSONResponse = new JSONObject(response); reCaptchaResponse = JSONResponse.getBoolean("success"); } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) { resp.sendRedirect("/registration?captchaError=1"); } else { if (account.equals("yes")) { password = params.get("password")[0]; confPassword = params.get("confPassword")[0]; } Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly(); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) { if (users.size() != 0) { resp.sendRedirect("/registration?userError=1"); } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) { resp.sendRedirect("/registration?passwordError=1"); } else { resp.sendRedirect("/registration?updated=1"); } } else { Entity registration = new Entity("registration"); registration.setProperty("registrationType", registrationType); registration.setProperty("account", account); registration.setProperty("schoolName", schoolName); registration.setProperty("schoolLevel", schoolLevel); registration.setProperty("name", name); registration.setProperty("classification", classification); registration.setProperty("studentData", new Text(studentData)); registration.setProperty("email", email); registration.setProperty("paid", ""); registration.setProperty("timestamp", new Date()); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) contestInfo.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); if (account.equals("yes") && password != null && password.length() > 0 && email != null) { Entity user = new Entity("user"); String hash = Password.getSaltedHash(password); user.setProperty("name", name); user.setProperty("school", schoolName); user.setProperty("schoolLevel", schoolLevel); user.setProperty("user-id", email); user.setProperty("salt", hash.split("\\$")[0]); user.setProperty("hash", hash.split("\\$")[1]); datastore.put(user); } txn.commit(); sess.setAttribute("props", registration.getProperties()); if (email != null) { Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); String url = req.getRequestURL().toString(); url = url.substring(0, url.indexOf("/", 7)); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name)); msg.setSubject("Thank you for your registration!"); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("url", url); context.put("cost", cost); context.put("title", contestInfo.getProperty("title")); context.put("account", account.equals("yes")); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "registrationEmail", ((Text) contestInfo.getProperty("registrationEmail")).getValue()); msg.setContent(sw.toString(), "text/html"); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } resp.sendRedirect("/registration?updated=1"); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { String contentType;/*from w w w . j a v a2 s . com*/ String fileExtension; String nameSuffix; JobExecutionContext jobExecutionContext; logger.debug("IN"); try { contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); nameSuffix = dispatchContext.getNameSuffix(); jobExecutionContext = dispatchContext.getJobExecutionContext(); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; int smptPort = 25; if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); /* if( (user==null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); if( (pass==null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); */ String mailTos = ""; List dlIds = dispatchContext.getDlIds(); Iterator it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); List emails = new ArrayList(); emails = dl.getEmails(); Iterator j = emails.iterator(); while (j.hasNext()) { Email e = (Email) j.next(); String email = e.getEmail(); String userTemp = e.getUserId(); IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp); if (ObjectsAccessVerifier.canSee(document, userProfile)) { if (j.hasNext()) { mailTos = mailTos + email + ","; } else { mailTos = mailTos + email; } } } } if ((mailTos == null) || mailTos.trim().equals("")) { throw new Exception("No recipient address found"); } String[] recipients = mailTos.split(","); //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); Session session = null; if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) { props.put("mail.smtp.auth", "false"); session = Session.getInstance(props); logger.debug("Connecting to mail server without authentication"); } else { props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(user, pass); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } session = Session.getInstance(props, auth); logger.debug("Connecting to mail server with authentication"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder(); String subject = document.getName() + nameSuffix; msg.setSubject(subject); // create and fill the first message part //MimeBodyPart mbp1 = new MimeBodyPart(); //mbp1.setText(mailTxt); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType, document.getName() + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); //mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } if (jobExecutionContext.getNextFireTime() == null) { String triggername = jobExecutionContext.getTrigger().getName(); dlIds = dispatchContext.getDlIds(); it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl, (document.getId()).intValue(), triggername); } } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:dk.netarkivet.common.utils.EMailUtils.java
/** * Send an email, possibly forgiving errors. * * @param to The recipient of the email. Separate multiple recipients with * commas. Supports only adresses of the type 'john@doe.dk', not * 'John Doe <john@doe.dk>' * @param from The sender of the email.//from w w w . j ava 2 s.com * @param subject The subject of the email. * @param body The body of the email. * @param forgive On true, will send the email even on invalid email * addresses, if at least one recipient can be set, on false, will * throw exceptions on any invalid email address. * * * @throws ArgumentNotValid If either parameter is null, if to, from or * subject is the empty string, or no recipient * can be set. If "forgive" is false, also on * any invalid to or from address. * @throws IOFailure If the message cannot be sent for some reason. */ public static void sendEmail(String to, String from, String subject, String body, boolean forgive) { ArgumentNotValid.checkNotNullOrEmpty(to, "String to"); ArgumentNotValid.checkNotNullOrEmpty(from, "String from"); ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject"); ArgumentNotValid.checkNotNull(body, "String body"); Properties props = new Properties(); props.put(MAIL_FROM_PROPERTY_KEY, from); props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER)); Session session = Session.getDefaultInstance(props); Message msg = new MimeMessage(session); // to might contain more than one e-mail address for (String toAddressS : to.split(",")) { try { InternetAddress toAddress = new InternetAddress(toAddressS.trim()); msg.addRecipient(Message.RecipientType.TO, toAddress); } catch (AddressException e) { if (forgive) { log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e); } else { throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address", e); } } catch (MessagingException e) { if (forgive) { log.warn("To address '" + toAddressS + "' could not be set in email", e); } else { throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e); } } } try { if (msg.getAllRecipients().length == 0) { throw new ArgumentNotValid("No valid recipients in '" + to + "'"); } } catch (MessagingException e) { throw new ArgumentNotValid("Message invalid after setting" + " recipients", e); } try { InternetAddress fromAddress = null; fromAddress = new InternetAddress(from); msg.setFrom(fromAddress); } catch (AddressException e) { throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e); } catch (MessagingException e) { if (forgive) { log.warn("From address '" + from + "' could not be set in email", e); } else { throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e); } } try { msg.setSubject(subject); msg.setContent(body, MIMETYPE); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to + "'. Body:\n" + body, e); } }
From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java
private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails) throws UIException, JSONException { String token = createToken(csid); EmailData ed = spec.getEmailData();//from w w w. j a v a 2 s . c o m String[] recipients = new String[1]; /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */ String messagebase = ed.getPasswordResetMessage(); String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam; String message = messagebase.replaceAll("\\{\\{link\\}\\}", link); String greeting = userdetails.getJSONObject("fields").getString("screenName"); message = message.replaceAll("\\{\\{greeting\\}\\}", greeting); message = message.replaceAll("\\\\n", "\\\n"); message = message.replaceAll("\\\\r", "\\\r"); String SMTP_HOST_NAME = ed.getSMTPHost(); String SMTP_PORT = ed.getSMTPPort(); String subject = ed.getPasswordResetSubject(); String from = ed.getFromAddress(); if (ed.getToAddress().isEmpty()) { recipients[0] = emailparam; } else { recipients[0] = ed.getToAddress(); } Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", ed.doSMTPAuth()); props.put("mail.debug", ed.doSMTPDebug()); props.put("mail.smtp.port", SMTP_PORT); Session session = Session.getDefaultInstance(props); // XXX fix to allow authpassword /username session.setDebug(debug); Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message); Transport.send(msg); } catch (AddressException e) { throw new UIException("AddressException: " + e.getMessage()); } catch (MessagingException e) { throw new UIException("MessagingException: " + e.getMessage()); } return true; }
From source file:org.infoglue.cms.util.mail.MailService.java
/** * *///from w w w . j av a 2s .c o m private Message createMessage(String from, String to, String bcc, String subject, String content, String contentType, String encoding) throws SystemException { try { final Message message = new MimeMessage(this.session); String contentTypeWithEncoding = contentType + ";charset=" + encoding; //message.setContent(content, contentType); message.setFrom(createInternetAddress(from)); message.setRecipient(Message.RecipientType.TO, createInternetAddress(to)); if (bcc != null) message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc)); //message.setSubject(subject); ((MimeMessage) message).setSubject(subject, encoding); //message.setText(content); message.setDataHandler( new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding))); //message.setText(content); //message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html"))); return message; } catch (MessagingException e) { throw new Bug("Unable to create the message.", e); } }
From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java
@Override public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body, List<NodeRef> attachments, boolean html) throws Exception { EmailConfig config = getConfig();/* w ww . j a v a2 s. com*/ EmailProvider provider = getEmailProvider(config.getProviderId()); Properties props = System.getProperties(); String prefix = "mail." + provider.getOutgoingProto() + "."; props.put(prefix + "host", provider.getOutgoingServer()); props.put(prefix + "port", provider.getOutgoingPort()); props.put(prefix + "auth", "true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName())); if (to != null) { InternetAddress[] recipients = new InternetAddress[to.size()]; for (int i = 0; i < to.size(); i++) recipients[i] = new InternetAddress(to.get(i)); msg.setRecipients(Message.RecipientType.TO, recipients); } if (cc != null) { InternetAddress[] recipients = new InternetAddress[cc.size()]; for (int i = 0; i < cc.size(); i++) recipients[i] = new InternetAddress(cc.get(i)); msg.setRecipients(Message.RecipientType.CC, recipients); } if (bcc != null) { InternetAddress[] recipients = new InternetAddress[bcc.size()]; for (int i = 0; i < bcc.size(); i++) recipients[i] = new InternetAddress(bcc.get(i)); msg.setRecipients(Message.RecipientType.BCC, recipients); } msg.setSubject(subject); msg.setHeader("X-Mailer", "Alvex Emailer"); msg.setSentDate(new Date()); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); if (body != null) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body, "utf-8", html ? "html" : "plain"); multipart.addBodyPart(messageBodyPart); } if (attachments != null) for (NodeRef att : attachments) { messageBodyPart = new MimeBodyPart(); String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME); messageBodyPart .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService))); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto()); t.connect(config.getUsername(), config.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
From source file:com.jvoid.customers.customer.service.CustomerMasterService.java
public void sendEmail(String email, String password) { Properties properties = System.getProperties(); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", false); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", 587); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("test@example.com", "test123"); }/*from w w w .ja v a 2s. c o m*/ }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("toaddress@example.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Reset Password"); String content = "Your new password is " + password; message.setText(content); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message//from w w w . j av a 2 s. co m * * @param recipients Recipients of the message that will be sent * @param subject The subject of the message * @param body The body of the message * @param config A mail server configuration to use * @throws Exception */ @Override public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config) throws EmailException { verifyParameters(recipients, config); if (!config.isEnabled()) { log.debug("Ignoring requested mail delivery. The given configuration is disabled."); return; } boolean debugEnabled = log.isDebugEnabled(); Properties properties = new Properties(); properties.put("mail.smtp.host", config.getHost()); properties.put("mail.smtp.port", Integer.toString(config.getPort())); properties.put("mail.smtp.quitwait", "false"); //Default protocol String protocol = "smtp"; //Enable TLS if set if (config.isUseTls()) { properties.put("mail.smtp.starttls.enable", "true"); } //Enable SSL if set boolean useSsl = config.isUseSsl(); if (useSsl) { properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort())); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); //Requires special protocol protocol = "smtps"; } //Set debug property if enabled by the logger properties.put("mail.debug", debugEnabled); Authenticator authenticator = null; if (!StringUtils.isEmpty(config.getUsername())) { properties.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }; } Session session = Session.getInstance(properties, authenticator); Message message = new MimeMessage(session); String subjectPrefix = config.getSubjectPrefix(); String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject; try { message.setSubject(fullSubject); if (!StringUtils.isEmpty(config.getFrom())) { InternetAddress addressFrom = new InternetAddress(config.getFrom()); message.setFrom(addressFrom); } InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } message.addRecipients(Message.RecipientType.TO, addressTo); //Create multi-part message in case we want to add html support Multipart multipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(body, "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); //Set debug property if enabled by the logger session.setDebug(debugEnabled); //Connect and send Transport transport = session.getTransport(protocol); if (useSsl) { transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { String em = e.getMessage(); throw new EmailException( "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n", e); } }
From source file:org.sofun.platform.notification.NotificationServiceImpl.java
@Override public void sendEmail(Member member, Map<String, String> params) throws CoreException { final String emailsStr = params.get("emails"); String[] emails = null;//from w w w .j a va 2 s .c o m if (emailsStr != null) { emails = params.get("emails").split(","); } String format = params.get("format"); if (format == null) { format = "text/html"; } Message message = new MimeMessage(mailer); final String encodingOptions = format + "; charset=UTF-8"; try { message.setHeader("Content-Type", encodingOptions); String from = params.get("from"); if (from == null || from.equals("")) { message.setFrom(new InternetAddress(CoreConstants.SOFUN_MAIL_FROM)); } else { message.setFrom(new InternetAddress(from)); } InternetAddress to[] = null; if (emails == null) { to = new InternetAddress[1]; to[0] = new InternetAddress(member.getEmail()); } else { to = new InternetAddress[emails.length]; for (int i = 0; i < emails.length; i++) { to[i] = new InternetAddress(emails[i]); } } message.setRecipients(Message.RecipientType.TO, to); message.setSubject(params.get("subject")); String body = params.get("body"); if (body != null) { body = body.replaceAll("(\\r|\\n)", "<p/>"); } VelocityEngine ve = null; try { ve = getVelocityEngine(); } catch (Exception e) { throw new CoreException(e.getMessage()); } Template t = ve.getTemplate(params.get("templateId")); StringWriter writer = new StringWriter(); VelocityContext context = new VelocityContext(); // Add Member in velocity context. context.put("member", member); context.put("body", body); // Add all incoming params in velocity context. for (Map.Entry<String, String> entry : params.entrySet()) { context.put(entry.getKey(), entry.getValue()); } t.merge(context, writer); message.setContent(writer.toString(), encodingOptions); Transport.send(message); String logEmails; if (emails != null) { logEmails = emailsStr; } else { logEmails = member.getEmail(); } log.info("Sending an email to=" + logEmails); } catch (MessagingException e) { log.error("Failed to send an email. See error below."); throw new CoreException(e.getMessage()); } }