List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:com.waveerp.sendMail.java
public void sendMsgSSL(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc) throws Exception { // 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.host", strHost); props.put("mail.smtp.socketFactory.port", strPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", strPort); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }/* ww w. j a va 2 s . co m*/ }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(strSource)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination)); message.setSubject(strSubject); message.setText(strMsg); Transport.send(message); //System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } //log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass ); }
From source file:org.apache.lens.server.query.QueryEndNotifier.java
/** Send mail. * * @param host the host * @param port the port * @param email the email * @param mailSmtpTimeout the mail smtp timeout * @param mailSmtpConnectionTimeout the mail smtp connection timeout */ public static void sendMail(String host, String port, Email email, int mailSmtpTimeout, int mailSmtpConnectionTimeout) throws Exception { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(email.getFrom())); for (String recipient : email.getTo().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); }//from w ww. j a va2 s .com if (email.getCc() != null && email.getCc().length() > 0) { for (String recipient : email.getCc().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient)); } } message.setSubject(email.getSubject()); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(email.getMessage()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); }
From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java
/** * Send an email to the given email address with the given subject line, * using contents generated from the given template and parameters. * * @param templateName The name of the template used to generate the * contents of the email./*from w ww . j av a2 s . c o m*/ * @param subject The subject for the email being sent. * @param emailAddress Sends the email to this address. * @param params The template is merged with these parameters to generate * the content of the email. * @throws EmailException Thrown if there are any errors in generating * content from the template, composing the email, or sending the email. */ private void sendMessage(final String templateName, final String subject, final String emailAddress, final Map<String, Object> params) throws EmailException { Writer stringWriter = new StringWriter(); try { Template template = this.configuration.getTemplate(templateName); template.process(params, stringWriter); } catch (TemplateException | IOException e) { throw new EmailException(e); } String content = stringWriter.toString(); MimeMessage message = new MimeMessage(this.session); try { InternetAddress fromEmailAddress = null; String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress(); if (fromEmailAddressStr != null) { fromEmailAddress = new InternetAddress(fromEmailAddressStr); } if (fromEmailAddress == null) { fromEmailAddress = InternetAddress.getLocalAddress(this.session); } if (fromEmailAddress == null) { try { fromEmailAddress = new InternetAddress( "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException ex) { fromEmailAddress = new InternetAddress("no-reply@localhost"); } } message.setFrom(fromEmailAddress); message.setSubject(subject); message.setContent(content, "text/plain"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSender(fromEmailAddress); Transport.send(message); } catch (MessagingException e) { LOGGER.error("Error sending the following email message:"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { message.writeTo(out); out.close(); } catch (IOException | MessagingException ex) { try { out.close(); } catch (IOException ignore) { } } LOGGER.error(out.toString()); throw new EmailException(e); } }
From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java
public void send(EmailModel model) throws EmailException { if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email: " + model); if (model == null) throw new NullPointerException("model"); Properties emailProps;/*from w w w .j a v a 2 s. c o m*/ Session emailSession; // set the relay host as a property of the email session emailProps = new Properties(); emailProps.setProperty("mail.transport.protocol", "smtp"); emailProps.put("mail.smtp.host", host); emailProps.setProperty("mail.smtp.port", String.valueOf(port)); // set the timeouts emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS)); emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS)); if (LOGGER.isDebugEnabled()) LOGGER.debug("Email properties: " + emailProps); // set up email session emailSession = Session.getInstance(emailProps, null); emailSession.setDebug(false); String from; String displayFrom; String body; String subject; List<EmailAttachment> attachments; if (model.getFrom() == null) throw new NullPointerException("from"); if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc()) && MiscUtils.isEmpty(model.getCc())) throw new IllegalArgumentException("model has no addresses"); from = model.getFrom(); displayFrom = model.getDisplayFrom(); body = model.getBody(); subject = model.getSubject(); attachments = model.getAttachments(); MimeMessage emailMessage; InternetAddress emailAddressFrom; // create an email message from the current session emailMessage = new MimeMessage(emailSession); // set the from try { emailAddressFrom = new InternetAddress(from, displayFrom); emailMessage.setFrom(emailAddressFrom); } catch (Exception e) { throw new IllegalStateException(e); } if (!MiscUtils.isEmpty(model.getTo())) setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO); if (!MiscUtils.isEmpty(model.getCc())) setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC); if (!MiscUtils.isEmpty(model.getBcc())) setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC); try { if (!MiscUtils.isEmpty(subject)) emailMessage.setSubject(subject); Multipart multipart = new MimeMultipart(); if (body != null) { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); //fill message String bodyContentType; // body = Utils.base64Encode(body); bodyContentType = "text/html; charset=UTF-8"; messageBodyPart.setContent(body, bodyContentType); //Content-Transfer-Encoding : base64 // messageBodyPart.addHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(messageBodyPart); } // Part two is attachment if (attachments != null && !attachments.isEmpty()) { try { for (EmailAttachment a : attachments) { MimeBodyPart attachBodyPart = new MimeBodyPart(); // don't base 64 encode DataSource source = new StreamDataSource( new DefaultStreamFactory(a.getInputStream(), false), a.getName(), a.getContentType()); attachBodyPart.setDataHandler(new DataHandler(source)); attachBodyPart.setFileName(a.getName()); attachBodyPart.setHeader("Content-Type", a.getContentType()); attachBodyPart.addHeader("Content-Transfer-Encoding", "base64"); // add the attachment to the message multipart.addBodyPart(attachBodyPart); } } // close all the input streams finally { for (EmailAttachment a : attachments) MiscUtils.closeStream(a.getInputStream()); } } // set the content emailMessage.setContent(multipart); emailMessage.saveChanges(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email message: " + emailMessage); Transport.send(emailMessage); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email complete."); } catch (Exception e) { throw new EmailException(e); } }
From source file:net.timbusproject.extractors.pojo.CallBack.java
public void sendEmail(String to, String subject, String body) { final String fromUser = fromMail; final String passUser = password; Properties props = new Properties(); props.put("mail.smtp.host", smtp); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.auth", mailAuth); props.put("mail.smtp.port", port); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromUser, passUser); }/*from w ww .j av a2 s . c o m*/ }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromUser)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText);// www . jav a 2s. co m multipart.addBodyPart(part); // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:com.quinsoft.zeidon.zeidonoperations.ZDRVROPR.java
public int CreateSeeMessage(int lConnection, String szSMTPServer, String szUserEmailAddress, String szRecipientEmailAddress, String szCCAddress, String szBCCAddress, String szSubjectText, int MimeType, String szMessageBody, String string4, String string5, int attachmentFlag, String szAttachmentFileName, String szUserEmailName, String szUserEmailPassword) { InternetAddress fromAddress = null;/* w w w. ja v a2s. com*/ String host = szSMTPServer; //enc-exhub.enc-ad.enc.edu String from = szUserEmailAddress; String to[] = szRecipientEmailAddress.split("[\\s,;]+"); InternetAddress[] toAddress = new InternetAddress[to.length]; String cc[] = szCCAddress.split("[\\s,;]+"); InternetAddress[] ccAddress = new InternetAddress[cc.length]; String bcc[] = szBCCAddress.split("[\\s,;]+"); InternetAddress[] bccAddress = new InternetAddress[bcc.length]; //String host = "enc-exhub.enc-ad.enc.edu"; //String from = "kellysautter@comcast.net"; //String to = "kellysautter@comcast.net"; // Set properties Properties props = new Properties(); //mail.smtp.sendpartial props.put("mail.smtp.host", host); props.put("mail.debug", "true"); // Get session // Going to use getDefaultInstance // If I get java.lang.SecurityException: Access to default session denied // then it said to go use .getInstance(props). Session session = Session.getDefaultInstance(props); try { // Instantiate a message Message msg = new MimeMessage(session); try { if (from != null && !from.isEmpty()) fromAddress = new InternetAddress(from); if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty()) { for (int iCnt = 0; iCnt < to.length; iCnt++) { toAddress[iCnt] = new InternetAddress(to[iCnt]); } } if (szCCAddress != null && !szCCAddress.isEmpty()) { for (int iCnt = 0; iCnt < cc.length; iCnt++) { ccAddress[iCnt] = new InternetAddress(cc[iCnt]); } } if (szBCCAddress != null && !szBCCAddress.isEmpty()) { for (int iCnt = 0; iCnt < bcc.length; iCnt++) { bccAddress[iCnt] = new InternetAddress(bcc[iCnt]); } } } catch (AddressException e) { task.log().error("*** CreateSeeMessage: setting addresses **** "); task.log().error(e); return -1; } // Set the FROM message msg.setFrom(fromAddress); if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty()) msg.setRecipients(Message.RecipientType.TO, toAddress); if (szCCAddress != null && !szCCAddress.isEmpty()) msg.setRecipients(Message.RecipientType.CC, ccAddress); if (szBCCAddress != null && !szBCCAddress.isEmpty()) msg.setRecipients(Message.RecipientType.BCC, bccAddress); // Set the message subject and date we sent it. msg.setSubject(szSubjectText); msg.setSentDate(new Date()); // Set message content msg.setText(szMessageBody); // Send the message Transport.send(msg); } catch (MessagingException mex) { task.log().error("*** CreateSeeMessage: Transport.send error **** "); task.log().error(mex); // Email was bad? if (mex instanceof SendFailedException) return -1; // SMTP connection bad? return -2; } return 0; }
From source file:org.entermedia.email.PostMail.java
public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject, String inHtml, String inText, String from, List inAttachments, Map inProperties) throws MessagingException { // Set the host smtp address Properties props = new Properties(); // create some properties and get the default Session props.put("mail.smtp.host", fieldSmtpServer); props.put("mail.smtp.port", String.valueOf(getPort())); props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString()); if (isSslEnabled()) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }//from w w w . j av a2s . c o m Session session = null; if (isEnableTls()) { props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword()); } }); } else if (fieldSmtpSecured) { SmtpAuthenticator auth = new SmtpAuthenticator(); session = Session.getInstance(props, auth); } else { session = Session.getInstance(props); } // session.setDebug(debug); // create a message Message msg = new MimeMessage(session); MimeMultipart mp = null; // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, // "text/html"))); if (inAttachments != null && inAttachments.size() == 0) { inAttachments = null; } if (inText != null && inHtml != null || inAttachments != null) { // Create an "Alternative" Multipart message mp = new MimeMultipart("mixed"); if (inText != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inText, "text/plain"); mp.addBodyPart(messageBodyPart); } if (inHtml != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inHtml, "text/html"); mp.addBodyPart(messageBodyPart); } if (inAttachments != null) { for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) { String filename = (String) iterator.next(); File file = new File(filename); if (file.exists() && !file.isDirectory()) { // create the second message part MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } } } msg.setContent(mp); } else if (inHtml != null) { msg.setContent(inHtml, "text/html"); } else { msg.setContent(inText, "text/plain"); } // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); //msg.setRecipient(RecipientType.BCC, addressFrom); msg.setSentDate(new Date()); if (recipients == null || recipients.isEmpty()) { throw new MessagingException("No recipients specified"); } InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]); msg.setRecipients(Message.RecipientType.TO, addressTo); //add bcc if (blindrecipients != null && !blindrecipients.isEmpty()) { InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]); msg.setRecipients(Message.RecipientType.BCC, addressBcc); } // Optional : You can also set your custom headers in the Email if you // Want // msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); // Transport tr = session.getTransport("smtp"); // tr.connect(serverandport[0], null, null); // msg.saveChanges(); // don't forget this // tr.sendMessage(msg, msg.getAllRecipients()); // tr.close(); // msg.setContent(msg, "text/plain"); Transport.send(msg); log.info("sent email " + subject); }
From source file:com.netspective.commons.message.SendMail.java
public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException, MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException { if (from == null) throw new SendMailNoFromAddressException("No FROM address provided."); if (to == null && cc == null && bcc == null) throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided."); Properties props = System.getProperties(); props.put("mail.smtp.host", host.getTextValue(vc)); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); if (headers != null) { List headersList = headers.getHeaders(); for (int i = 0; i < headersList.size(); i++) { Header header = (Header) headersList.get(i); message.setHeader(header.getName(), header.getValue().getTextValue(vc)); }// www . j a v a2 s .c o m } message.setFrom(new InternetAddress(from.getTextValue(vc))); if (replyTo != null) message.setReplyTo(getAddresses(replyTo.getValue(vc))); if (to != null) message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc))); if (cc != null) message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc))); if (bcc != null) message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc))); if (subject != null) message.setSubject(subject.getTextValue(vc)); if (body != null) { StringWriter messageText = new StringWriter(); body.process(messageText, vc, bodyTemplateVars); message.setText(messageText.toString()); } Transport.send(message); }
From source file:org.forumj.email.FJEMail.java
public static void sendMail(String to, String from, String host, String subject, String text) throws ConfigurationException, AddressException, MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", host); String mailDebug = FJConfiguration.getConfig().getString("mail.debug"); props.put("mail.debug", mailDebug == null ? "false" : mailDebug); Session session = Session.getInstance(props); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.addHeader("charset", "UTF-8"); msg.setSubject(subject);/*from w w w . j a va 2 s. c o m*/ msg.setSentDate(new Date()); msg.setDataHandler(new DataHandler(new HTMLDataSource(text))); Transport.send(msg); }