List of usage examples for javax.mail.internet MimeMessage setFrom
@Override public void setFrom() throws MessagingException
InternetAddress.getLocalAddress
method. From source file:com.flexive.shared.FxMailUtils.java
/** * Sends an email//w w w . j a v a2s. c o m * * @param SMTPServer IP Address of the SMTP server * @param subject subject of the email * @param textBody plain text * @param htmlBody html text * @param to recipient * @param cc cc recepient * @param bcc bcc recipient * @param from sender * @param replyTo reply-to address * @param mimeAttachments strings containing mime encoded attachments * @throws FxApplicationException on errors */ public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to, String cc, String bcc, String from, String replyTo, String... mimeAttachments) throws FxApplicationException { try { // Set the mail server java.util.Properties properties = System.getProperties(); if (SMTPServer != null) properties.put("mail.smtp.host", SMTPServer); // Get a session and create a new message javax.mail.Session session = javax.mail.Session.getInstance(properties, null); MimeMessage msg = new MimeMessage(session); // Set the sender if (StringUtils.isBlank(from)) msg.setFrom(); // Uses local IP Adress and the user under which the server is running else { msg.setFrom(createAddress(from)); } if (!StringUtils.isBlank(replyTo)) msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false))); // Set the To, Cc and Bcc fields if (!StringUtils.isBlank(to)) msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false))); if (!StringUtils.isBlank(cc)) msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false))); if (!StringUtils.isBlank(bcc)) msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false))); // Set the subject msg.setSubject(subject, "UTF-8"); String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\""; StringBuilder body = new StringBuilder(5000); if (mimeAttachments.length > 0) { sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\""; body.append("This is a multi-part message in MIME format.\n\n"); body.append("--" + BOUNDARY2 + "\n"); body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n"); } if (textBody.length() > 0) { body.append("--" + BOUNDARY1 + "\n"); body.append("Content-Type: text/plain; charset=\"UTF-8\"\n"); body.append("Content-Transfer-Encoding: quoted-printable\n\n"); body.append(encodeQuotedPrintable(textBody)).append("\n"); } if (htmlBody.length() > 0) { body.append("--" + BOUNDARY1 + "\n"); body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n"); body.append("Content-Transfer-Encoding: quoted-printable\n\n"); if (htmlBody.toLowerCase().indexOf("<html>") < 0) { body.append("<HTML><HEAD>\n<TITLE></TITLE>\n"); body.append( "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n"); body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n"); } else body.append(encodeQuotedPrintable(htmlBody)).append("\n"); } body.append("\n--" + BOUNDARY1 + "--\n"); if (mimeAttachments.length > 0) { for (String mimeAttachment : mimeAttachments) { body.append("\n--" + BOUNDARY2 + "\n"); body.append(mimeAttachment).append("\n"); } body.append("\n--" + BOUNDARY2 + "--\n"); } msg.setDataHandler( new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType))); // Set the header msg.setHeader("X-Mailer", "JavaMailer"); // Set the sent date msg.setSentDate(new java.util.Date()); // Send the message javax.mail.Transport.send(msg); } catch (AddressException e) { throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef()); } catch (javax.mail.MessagingException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } catch (IOException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } catch (EncoderException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } }
From source file:com.unilever.audit.services2.ForgetPassword.java
@GET @Path("Email/{email}") @Produces("application/json") public String LoginIn(@PathParam("email") String email) throws IOException { boolean status = true; String error = null;/*w w w. j a va 2 s.c om*/ JSONObject result = new JSONObject(); Map<String, Object> hm = new HashMap<String, Object>(); hm.put("email", email); Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST .findOneByQuery("Merchandisers.findByEmail", hm); if (merchidisers == null) { status = false; error = "invalid email"; } else { Properties props = new Properties(); final String from = ""; final String password = ""; props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.user", from); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.password", password); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); session.setDebug(true); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, email); msg.setSubject("Unilever Confirmation"); msg.setSentDate(new Date()); msg.setText(""); Transport.send(msg); } catch (MessagingException ex) { // status = false; // error="Error Sending Email"; ex.printStackTrace(); } } result.put("status", status); result.put("error", error); System.out.println("----------------" + result.toString()); return result.toString(); }
From source file:com.emc.plants.service.impl.MailerBean.java
/** * Create a mail message and send it.// w w w.j a va 2 s.co m * * @param customerInfo Customer information. * @param orderKey * @throws MailerAppException */ public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException { try { EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey), customerInfo.getCustomerID()); Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: " + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents()); //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false)); msg.setSubject(eMessage.getSubject()); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(eMessage.getHtmlContents(), "us-ascii"); msg.setHeader("X-Mailer", "JavaMailer"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); Util.debug("\nMail sent successfully."); } catch (Exception e) { Util.debug("Error sending mail. Have mail resources been configured correctly?"); Util.debug("createAndSendMail exception : " + e); e.printStackTrace(); throw new MailerAppException("Failure while sending mail"); } }
From source file:be.fedict.eid.dss.model.bean.TaskMDB.java
private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype, byte[] attachment) { LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\""); String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class); if (null == smtpServer || smtpServer.trim().isEmpty()) { LOG.warn("no SMTP server configured"); return;// w ww .j a v a2 s .co m } String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class); if (null == mailFrom || mailFrom.trim().isEmpty()) { LOG.warn("no mail from address configured"); return; } LOG.debug("mail from: " + mailFrom); Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.from", mailFrom); String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class); if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) { subject = "[" + mailPrefix.trim() + "] " + subject; } Session session = Session.getInstance(props, null); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(); mimeMessage.setRecipients(RecipientType.TO, mailTo); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(messageBody); Multipart multipart = new MimeMultipart(); // first part is body multipart.addBodyPart(mimeBodyPart); // second part is attachment if (null != attachment) { MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype); attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource)); multipart.addBodyPart(attachmentMimeBodyPart); } mimeMessage.setContent(multipart); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("send failed, exception: " + e.getMessage(), e); } }
From source file:mx.unam.pixel.controller.MailController.java
public void enviaMensaje(String mensaje) { try {// w w w.j a v a2s . c om Properties props = new Properties(); // Nombre del host de correo, es smtp.gmail.com props.setProperty("mail.smtp.host", "smtp.gmail.com"); // TLS si est disponible props.setProperty("mail.smtp.starttls.enable", "true"); // Puerto de gmail para envio de correos props.setProperty("mail.smtp.port", "587"); // Nombre del usuario props.setProperty("mail.smtp.user", "ejemplo@gmail.com"); // Si requiere o no usuario y password para conectarse. props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); //session.setDebug(true); //Construimos el mensage MimeMessage message = new MimeMessage(session); InternetAddress cuenta = new InternetAddress("enrique.wps@gmail.com"); message.setFrom(); //Correo electronico que manda el mensaja message.addRecipient(Message.RecipientType.TO, new InternetAddress("vampa@ciencias.unam.mx")); message.setSubject("Test MUFFIN"); message.setText("Test Muffin Cuerpo"); // Abrimos la comunicacion Transport t = session.getTransport("smtp"); t.connect("dasds@gmail.com", "asdsadas"); // Ususario y contrasea t.sendMessage(message, message.getAllRecipients()); // Cierre t.close(); } catch (AddressException ex) { System.err.println("er"); } catch (MessagingException ex) { Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.googlecode.psiprobe.tools.Mailer.java
private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException { InternetAddress[] to = createAddresses(mailMessage.getToArray()); InternetAddress[] cc = createAddresses(mailMessage.getCcArray()); InternetAddress[] bcc = createAddresses(mailMessage.getBccArray()); if (to.length == 0) { to = InternetAddress.parse(defaultTo); }/*from www .j ava2s. co m*/ String subject = mailMessage.getSubject(); if (subjectPrefix != null && !subjectPrefix.equals("")) { subject = subjectPrefix + " " + subject; } MimeMultipart content = new MimeMultipart("related"); //Create attachments DataSource[] attachments = mailMessage.getAttachmentsArray(); for (int i = 0; i < attachments.length; i++) { DataSource attachment = attachments[i]; MimeBodyPart attachmentPart = createAttachmentPart(attachment); content.addBodyPart(attachmentPart); } //Create message body MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml()); content.addBodyPart(bodyPart); MimeMessage message = new MimeMessage(session); if (from == null) { message.setFrom(); //Uses mail.from property } else { message.setFrom(new InternetAddress(from)); } message.setRecipients(Message.RecipientType.TO, to); message.setRecipients(Message.RecipientType.CC, cc); message.setRecipients(Message.RecipientType.BCC, bcc); message.setSubject(subject); message.setContent(content); return message; }
From source file:org.hyperic.hq.bizapp.server.session.EmailManagerImpl.java
public void sendEmail(EmailRecipient[] addresses, String subject, String[] body, String[] htmlBody, Integer priority) {//from w w w. ja v a2s . c om MimeMessage mimeMessage = mailSender.createMimeMessage(); final StopWatch watch = new StopWatch(); try { InternetAddress from = getFromAddress(); if (from == null) { mimeMessage.setFrom(); } else { mimeMessage.setFrom(from); } // HHQ-5708 // remove any possible new line from the subject // the subject can be render form 'subject.gsp' file mimeMessage.setSubject(subject.replace("\r", "").replace("\n", "")); // If priority not null, set it in body if (priority != null) { switch (priority.intValue()) { case EventConstants.PRIORITY_HIGH: mimeMessage.addHeader("X-Priority", "1"); break; case EventConstants.PRIORITY_MEDIUM: mimeMessage.addHeader("X-Priority", "2"); break; default: break; } } // Send to each recipient individually (for D.B. SMS) for (int i = 0; i < addresses.length; i++) { mimeMessage.setRecipient(Message.RecipientType.TO, addresses[i].getAddress()); if (addresses[i].useHtml()) { mimeMessage.setContent(htmlBody[i], "text/html; charset=UTF-8"); if (log.isDebugEnabled()) { log.debug("Sending HTML Alert notification: " + subject + " to " + addresses[i].getAddress().getAddress() + "\n" + htmlBody[i]); } } else { if (log.isDebugEnabled()) { log.debug("Sending Alert notification: " + subject + " to " + addresses[i].getAddress().getAddress() + "\n" + body[i]); } mimeMessage.setContent(body[i], "text/plain; charset=UTF-8"); } mailSender.send(mimeMessage); } } catch (MessagingException e) { log.error("MessagingException in sending email: [" + subject + "]\nmailServer = [" + mailSession.getProperties() + "]", e); } catch (MailException me) { log.error("MailException in sending email: [" + subject + "]\nmailServer = [" + mailSession.getProperties() + "]", me); } catch (Exception ex) { log.error( "Error in sending email: [" + subject + "]\nmailServer = [" + mailSession.getProperties() + "]", ex); } finally { if (log.isDebugEnabled()) { log.debug("Sending email using mailServer=" + mailSession.getProperties() + " took " + watch.getElapsed() + " ms."); } if (watch.getElapsed() >= mailSmtpConnectiontimeout || (watch.getElapsed() >= mailSmtpTimeout)) { log.warn("Sending email using mailServer=" + mailSmtpHost + " took " + watch.getElapsed() + " ms. Please check with your mail administrator."); } } }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
/** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail>//from ww w. ja v a2 s. c o m * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; if (bodyPart.getLocalName().equals("text")) { // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; } else if (bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; } else if (bodyPart.getLocalName().equals("generic")) { // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); } // Now, time to store it if (content != null && contentType != null && contentType.length() > 0) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (attachments.size() > 0) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; }