List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException, SendFailedException, MessagingException, IOException { String fromAddress = email.getHeader(Message.Field.FROM); if (fromAddress == null) { throw new MessagingException("Unable to send without a 'from' address."); }/* www. j a v a2s .co m*/ // transform to a MimeMessage ArrayList<String> invalids = new ArrayList<String>(); // convert and validate the 'from' address InternetAddress from = new InternetAddress(fromAddress, true); // convert and validate reply to addresses String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO); InternetAddress[] replyTo = emails2Internets(replyTos, invalids); // convert and validate the 'to' addresses String tos = email.getHeader(Message.Field.TO); InternetAddress[] to = emails2Internets(tos, invalids); // convert and validate 'cc' addresses String ccs = email.getHeader(EmailMessage.Field.CC); InternetAddress[] cc = emails2Internets(ccs, invalids); // convert and validate 'bcc' addresses String bccs = email.getHeader(EmailMessage.Field.BCC); InternetAddress[] bcc = emails2Internets(bccs, invalids); int totalRcpts = to.length + cc.length + bcc.length; if (totalRcpts == 0) { throw new MessagingException("No recipients to send to."); } MimeMessage mimeMsg = new MimeMessage(session); mimeMsg.setFrom(from); mimeMsg.setReplyTo(replyTo); mimeMsg.setRecipients(RecipientType.TO, to); mimeMsg.setRecipients(RecipientType.CC, cc); mimeMsg.setRecipients(RecipientType.BCC, bcc); // add in any additional headers Map<String, String> headers = email.getHeaders(); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> header : headers.entrySet()) { mimeMsg.setHeader(header.getKey(), header.getValue()); } } // add the content to the message List<Message> parts = email.getParts(); if (parts == null || parts.size() == 0) { setContent(mimeMsg, email); } else { // create a multipart container Multipart multipart = new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); setContent(msgBodyPart, email); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (Message part : parts) { addPart(multipart, part); } // set the multipart container as the content of the message mimeMsg.setContent(multipart); } if (allowTransport) { // send Transport.send(mimeMsg); } else { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); mimeMsg.writeTo(output); String emailString = output.toString(); LOG.info(emailString); observable.notifyObservers(emailString); } catch (IOException e) { LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e); } } }
From source file:ftpclient.FTPManager.java
public boolean sendUserMail(String uploadedFileName) { if (settings != null) { try {/*from www.j a v a2 s . c o m*/ String userEmail = db.getUserEmail(uid); Properties props = System.getProperties(); props.setProperty("mail.smtp.host", settings.getSenderEmailHost()); props.setProperty("mail.smtp.auth", "true"); // props.put("mail.smtp.starttls.enable", "true"); // props.put("mail.smtp.port", "587"); Session s = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(settings.getSenderLogin(), new String(settings.getSenderPassword())); } }); MimeMessage msg = new MimeMessage(s); msg.setFrom(settings.getSenderEmail()); msg.addRecipients(Message.RecipientType.TO, userEmail); msg.setSubject("FTP action"); msg.setText("You have succesfully uploaded file " + uploadedFileName); Transport.send(msg); return true; } catch (MessagingException ex) { Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex); return false; } } else { return false; } }
From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java
public void sendMail(Mail mail) { LOG.debug("sendEmail() to: " + mail.getRecipient()); try {/* ww w . j a v a2 s .c o m*/ Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator); session.setDebug(false); MimeMessage msg = new MimeMessage(session); msg.setFrom(m_bag.m_fromAddress); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient())); msg.setSubject(mail.getSubject()); msg.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart txtmbp = new MimeBodyPart(); txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE); mp.addBodyPart(txtmbp); List<String> attachments = mail.getAttachments(); for (Iterator<String> it = attachments.iterator(); it.hasNext();) { MimeBodyPart mbp = new MimeBodyPart(); String filename = it.next(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mp.addBodyPart(mbp); } msg.setContent(mp); if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null) && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) { cheat(msg, m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@"))); } Transport.send(msg); LOG.info("Successfully send the mail to " + mail.getRecipient()); } catch (Throwable e) { LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e); LOG.debug("Details:", e); } }
From source file:org.georchestra.console.mailservice.Email.java
protected void sendMsg(String msg) throws AddressException, MessagingException { if (LOG.isDebugEnabled()) { LOG.debug("body: " + msg); }//ww w. j a va 2 s.c om // Replace {publicUrl} token with the configured public URL msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl")); final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", smtpHost); session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString()); final MimeMessage message = new MimeMessage(session); if (isValidEmailAddress(from)) { message.setFrom(new InternetAddress(from)); } boolean validRecipients = false; for (String recipient : recipients) { if (isValidEmailAddress(recipient)) { validRecipients = true; message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } if (!validRecipients) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(from)); message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding); } else { message.setSubject(subject, subjectEncoding); } if (msg != null) { /* See http://www.rgagnon.com/javadetails/java-0321.html */ if ("true".equalsIgnoreCase(emailHtml)) { message.setContent(msg, "text/html; charset=" + bodyEncoding); } else { message.setContent(msg, "text/plain; charset=" + bodyEncoding); } LOG.debug(msg); } Transport.send(message); LOG.debug("email has been sent to:\n" + Arrays.toString(recipients)); }
From source file:org.nuxeo.ecm.automation.core.mail.Mailer.java
/** * Send a single email.//from w w w . j ava 2 s . c o m */ public void sendEmail(String from, String to, String subject, String body) throws MessagingException { // Here, no Authenticator argument is used (it is null). // Authenticators are used to prompt the user for user // name and password. MimeMessage message = new MimeMessage(getSession()); // the "from" address may be set in code, or set in the // config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(body); Transport.send(message); }
From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java
public boolean send() { String cc = null;//from ww w.j a v a 2 s . c o m String bcc = null; String from = props.getProperty("mail.from.default"); String to = props.getProperty("to"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject + "' and the body " + body); try { // Get a Session object Session session; if (authenticate) { Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } if (body != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } // need to create a multi-part message... // create the Multipart and add its parts to it // create and fill the first message part IPentahoStreamSource source = attachment; if (source == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:org.vulpe.commons.util.VulpeEmailUtil.java
/** * Send mail to recipients by Web Service. * * @param recipients//w w w .j ava 2 s.c o m * * @param subject * * @param body * * @param mailerService * * @throws VulpeSystemException * exception */ public static void sendMailByService(final String[] recipients, final String subject, final String body, final String mailerService) { try { final ResourceBundle bundle = ResourceBundle.getBundle("mail"); String mailFrom = ""; if (bundle.containsKey("mail.from")) { mailFrom = bundle.getString("mail.from"); } final InitialContext initialContext = new InitialContext(); final Session session = (Session) initialContext.lookup(mailerService); final Message message = new MimeMessage(session); message.setFrom(new InternetAddress(mailFrom)); for (String recipient : recipients) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } // msg.setRecipient(Message.RecipientType.TO, new // InternetAddress(to)); message.setSubject(subject); message.setText(body); Transport.send(message); } catch (Exception e) { LOG.error(e.getMessage()); } }
From source file:net.sourceforge.vulcan.mailer.EmailPlugin.java
void sendMessage(MimeMessage message) throws AddressException, MessagingException { Transport.send(message); }
From source file:com.bia.gmailjava.EmailService.java
/** * * @param addressTo// w w w. j a v a 2 s . c o m * @param subject * @param message * @throws AddressException * @throws MessagingException */ private void send(InternetAddress[] addressTo, String subject, String message) throws AddressException, MessagingException { Message msg = new MimeMessage(createSession()); InternetAddress addressFrom = new InternetAddress(USERNAME); msg.setFrom(addressFrom); msg.setRecipients(Message.RecipientType.TO, addressTo); // set bcc //InternetAddress[] bcc1 = getBCC(); //msg.setRecipients(Message.RecipientType.BCC, bcc1); // Setting the Subject and Content Type msg.setSubject(subject); //String message = comment; msg.setContent(message, EMAIL_CONTENT_TYPE); Transport.send(msg); }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MailUsersServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VitroRequest vreq = new VitroRequest(request); String confirmpage = "/confirmUserMail.jsp"; String errpage = "/contact_err.jsp"; String status = null; // holds the error status if (!FreemarkerEmailFactory.isConfigured(vreq)) { status = "This application has not yet been configured to send mail. " + "Email properties must be specified in the configuration properties file."; response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); return;/* ww w .j a v a2 s. co m*/ } String SPAM_MESSAGE = "Your message was flagged as spam."; boolean probablySpam = false; String spamReason = ""; String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer"); request.getSession().removeAttribute("commentsFormReferer"); if (originalReferer == null) { originalReferer = "none"; // (the following does not support cookie-less browsing:) // probablySpam = true; // status = SPAM_MESSAGE; } else { String referer = request.getHeader("Referer"); //Review how spam works? /*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) { probablySpam=true; status = SPAM_MESSAGE ; spamReason = "The form was not submitted from the Contact Us or Corrections page."; }*/ } String formType = vreq.getParameter("DeliveryType"); List<String> deliverToArray = null; int recipientCount = 0; String deliveryfrom = null; // get Individuals that the User mayEditAs deliverToArray = getEmailsForAllUserAccounts(vreq); //Removed all form type stuff b/c recipients pre-configured recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size(); if (recipientCount == 0) { //log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\""); throw new Error("To establish the Contact Us mail capability the system administrators must " + "specify at least one email address in the current portal."); } // obtain passed in form data with a simple trim on the values String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception String webuseremail = vreq.getParameter("webuseremail");//.trim(); String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify? //webusername = "hjk54"; //webuseremail = "hjk54@cornell.edu"; //comments = "following are comments"; webusername = webusername.trim(); deliveryfrom = webuseremail; comments = comments.trim(); //Removed spam filtering code StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix // from MyLibrary msgBuf.setLength(0); //msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator); msgBuf.append("<html>" + lineSeparator); msgBuf.append("<head>" + lineSeparator); msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator); msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator); msgBuf.append("</head>" + lineSeparator); msgBuf.append("<body>" + lineSeparator); msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator); msgBuf.append("<h4>From: " + webusername + " (" + webuseremail + ")" + " at IP address " + request.getRemoteAddr() + "</h4>" + lineSeparator); //Don't need any 'likely viewing page' portion to be emailed out to the others msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator); if (comments == null || comments.equals("")) { msgBuf.append("<p>BLANK MESSAGE</p>"); } else { msgBuf.append("<p>" + comments + "</p>"); } msgBuf.append("</body>" + lineSeparator); msgBuf.append("</html>" + lineSeparator); String msgText = msgBuf.toString(); Calendar cal = Calendar.getInstance(); /* outFile.println("<hr/>"); outFile.println(); outFile.println("<p>"+cal.getTime()+"</p>"); outFile.println(); if (probablySpam) { outFile.println("<p>REJECTED - SPAM</p>"); outFile.println("<p>"+spamReason+"</p>"); outFile.println(); } outFile.print( msgText ); outFile.println(); outFile.println(); outFile.flush(); // outFile.close(); */ Session s = FreemarkerEmailFactory.getEmailSession(vreq); //s.setDebug(true); try { // Construct the message MimeMessage msg = new MimeMessage(s); log.debug("trying to send message from servlet"); // Set the from address msg.setFrom(new InternetAddress(webuseremail)); // Set the recipient address if (recipientCount > 0) { InternetAddress[] address = new InternetAddress[recipientCount]; for (int i = 0; i < recipientCount; i++) { address[i] = new InternetAddress(deliverToArray.get(i)); } msg.setRecipients(Message.RecipientType.TO, address); } // Set the subject and text msg.setSubject(deliveryfrom); // add the multipart to the message msg.setContent(msgText, "text/html"); // set the Date: header msg.setSentDate(new Date()); log.debug("sending from servlet"); //if (!probablySpam) Transport.send(msg); // try to send the message via smtp - catch error exceptions } catch (AddressException e) { status = "Please supply a valid email address."; log.debug("Error - status is " + status); } catch (SendFailedException e) { status = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]"; log.error("Error - status is " + status); } catch (MessagingException e) { status = "The system was unable to deliver your mail. Please try again later. [MESSAGING]"; log.error("Error - status is " + status, e); } //outFile.flush(); //outFile.close(); // Redirect to the appropriate confirmation page if (status == null && !probablySpam) { // message was sent successfully response.sendRedirect("test?bodyJsp=" + confirmpage); } else { // exception occurred response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); } }