List of usage examples for javax.mail.internet MimeMessage setSentDate
@Override public void setSentDate(Date d) throws MessagingException
From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ContactMailController.java
private void sendMessage(Session s, String webuseremail, String webusername, String[] recipients, String deliveryfrom, String msgText) throws AddressException, SendFailedException, MessagingException { // Construct the message MimeMessage msg = new MimeMessage(s); //System.out.println("trying to send message from servlet"); // Set the from address try {//from w w w .ja v a 2 s.co m msg.setFrom(new InternetAddress(webuseremail, webusername)); } catch (UnsupportedEncodingException e) { log.error("Can't set message sender with personal name " + webusername + " due to UnsupportedEncodingException"); msg.setFrom(new InternetAddress(webuseremail)); } // Set the recipient address InternetAddress[] address = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { address[i] = new InternetAddress(recipients[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()); Transport.send(msg); // try to send the message via smtp - catch error exceptions }
From source file:org.j2free.email.EmailService.java
private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body, ContentType contentType, Priority priority, boolean ccSender) throws AddressException, MessagingException, RejectedExecutionException { MimeMessage message = new MimeMessage(session); message.setFrom(from);/*from ww w . j ava 2s. c om*/ message.setRecipients(Message.RecipientType.TO, recipients); for (Map.Entry<String, String> header : headers.entrySet()) message.setHeader(header.getKey(), header.getValue()); // CC the sender if they want if (ccSender) message.addRecipient(Message.RecipientType.CC, from); message.setReplyTo(new InternetAddress[] { from }); message.setSubject(subject); message.setSentDate(new Date()); if (contentType == ContentType.PLAIN) { // Just set the body as plain text message.setText(body, "UTF-8"); } else { MimeMultipart multipart = new MimeMultipart("alternative"); // Create the text part MimeBodyPart text = new MimeBodyPart(); text.setText(new HtmlFilter().filterForEmail(body), "UTF-8"); // Add the text part multipart.addBodyPart(text); // Create the HTML portion MimeBodyPart html = new MimeBodyPart(); html.setContent(body, ContentType.HTML.toString()); // Add the HTML portion multipart.addBodyPart(html); // set the message content message.setContent(multipart); } enqueue(message, priority); }
From source file:com.commoncoupon.mail.EmailProcessor.java
public Integer call() throws Exception { MimeMessage message = new MimeMessage(getSession()); try {//www . j ava 2s . com if (from != null && (from != null && from.trim() != "")) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (log.isDebugEnabled()) log.debug("Email sent from: " + sentFrom); } if (to != null && to.length > 0) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress((String) to[i]); if (log.isDebugEnabled()) log.debug("Sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null && cc.length > 0) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress((String) cc[i]); if (log.isDebugEnabled()) log.debug("Copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } message.setSentDate(new Date()); message.setSubject(subject); message.setContent(content, mimeType); Transport.send(message); } catch (Exception e) { log.error("Failed to send email.", e); return (1); } return (0); }
From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java
public boolean send() { try {//w w w . ja va2 s. c o m MimeMessage msg = new MimeMessage(mailSession); msg.setReplyTo(new Address[] { replyToAddress }); if (fromAddress == null) { msg.addFrom(new Address[] { replyToAddress }); } else { msg.addFrom(new Address[] { fromAddress }); } for (Recipient recipient : recipients) { msg.addRecipient(recipient.type, recipient.address); } msg.setSubject(subject); if (textContent.isEmpty()) { if (htmlContent.isEmpty()) { log.error("Message has neither text body nor HTML body"); } else { msg.setContent(htmlContent, "text/html"); } } else { if (htmlContent.isEmpty()) { msg.setContent(textContent, "text/plain"); } else { MimeMultipart content = new MimeMultipart("alternative"); addBodyPart(content, textContent, "text/plain"); addBodyPart(content, htmlContent, "text/html"); msg.setContent(content); } } msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (MessagingException e) { log.error("Failed to send message.", e); return false; } }
From source file:org.fireflow.service.email.send.MailSenderImpl.java
/** * TODO ?// ww w. j a va 2s . c o m * @param mailSession * @param mailMessage * @return * @throws MessagingException * @throws AddressException * @throws ServiceInvocationException */ private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage) throws AddressException, MessagingException { MimeMessage mimeMsg = new MimeMessage(mailSession); //1?set from //Assert.notNull(mailMessage.getFrom(),"From address must not be null"); mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom())); //2?set mailto List<String> mailToList = mailMessage.getMailToList(); InternetAddress[] addressList = new InternetAddress[mailToList.size()]; for (int i = 0; i < mailToList.size(); i++) { String mailTo = mailToList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.TO, addressList); //3?set cc List<String> ccList = mailMessage.getCarbonCopyList(); if (ccList != null && ccList.size() > 0) { addressList = new InternetAddress[ccList.size()]; for (int i = 0; i < ccList.size(); i++) { String mailTo = ccList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.CC, addressList); } //4?set subject mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset()); //5?set sentDate if (this.sentDate != null) { mimeMsg.setSentDate(sentDate); } //6?set email body Multipart multiPart = new MimeMultipart(); MimeBodyPart bp = new MimeBodyPart(); if (mailMessage.getBodyIsHtml()) bp.setContent(mailMessage.getBody(), CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset()); else bp.setText(mailMessage.getBody(), mailServiceDef.getCharset()); multiPart.addBodyPart(bp); mimeMsg.setContent(multiPart); //7?set attachment //TODO ? return mimeMsg; }
From source file:org.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;/* www . j av a 2 s . c o m*/ try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
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);/*from ww w . ja v a 2 s . c o 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:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java
/** * Sends an email to the given id including a link to the password page. The * link contains the refID.// w w w. j av a 2s.c o m * * @param emailType * - refers to the email that shall be sent, 0 sends an email for * newly registered users, 1 sends a standard password-reset * email * @param emailaddress * @param refID * @return */ public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) { String salutation = ""; if (user.getGender().equalsIgnoreCase("male")) { salutation = "geehrter Herr " + user.getName(); } else { salutation = "geehrte Frau " + user.getName(); } MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"), emailProperties.getProperty("mail.user.password")); // Login Properties props = (Properties) emailProperties.clone(); props.remove("mail.user"); props.remove("mail.user.password"); Session session = Session.getInstance(props, auth); String htmlContent = emailBody; htmlContent = htmlContent.replaceFirst("TITLE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".title")); htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT", emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject")); htmlContent = htmlContent.replaceFirst("HEADER1", emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1")); htmlContent = htmlContent.replaceFirst("MESSAGE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".message")); htmlContent = htmlContent.replaceFirst("SALUTATION", salutation); htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); htmlContent = htmlContent.replaceFirst("REFERER", refID); htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'"); htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'"); String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - " + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n" + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"); textContent = textContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); textContent = textContent.replaceFirst("REFERER", refID); textContent = textContent.replaceFirst("SALUTATION", salutation); textContent = textContent.replaceAll("<br>", "\n"); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress()); msg.setSentDate(new Date()); msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject")); Multipart mp = new MimeMultipart("alternative"); // plaintext MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(textContent); mp.addBodyPart(textPart); // html MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); MimeBodyPart imagePart = new MimeBodyPart(); DataSource fds = null; try { fds = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart.setDataHandler(new DataHandler(fds)); imagePart.setHeader("Content-ID", "header-image"); mp.addBodyPart(imagePart); MimeBodyPart imagePart2 = new MimeBodyPart(); DataSource fds2 = null; try { fds2 = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.dash")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart2.setDataHandler(new DataHandler(fds2)); imagePart2.setHeader("Content-ID", "dash"); mp.addBodyPart(imagePart2); msg.setContent(mp); Transport.send(msg); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); return false; } return true; }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email/*from ww w . j a v a 2 s. c om*/ * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email/*from ww w . j av a 2s . c o m*/ * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }