List of usage examples for javax.mail.internet MimeMessage addHeader
@Override public void addHeader(String name, String value) throws MessagingException
From source file:org.apache.james.core.builder.MimeMessageBuilder.java
public MimeMessage build() throws MessagingException { Preconditions.checkState(!(text.isPresent() && content.isPresent()), "Can not get at the same time a text and a content"); MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties())); if (text.isPresent()) { mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE)); }/* w w w.j ava2s . c om*/ if (content.isPresent()) { mimeMessage.setContent(content.get()); } if (sender.isPresent()) { mimeMessage.setSender(sender.get()); } if (subject.isPresent()) { mimeMessage.setSubject(subject.get()); } ImmutableList<InternetAddress> fromAddresses = from.build(); if (!fromAddresses.isEmpty()) { mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()])); } List<InternetAddress> toAddresses = to.build(); if (!toAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[toAddresses.size()])); } List<InternetAddress> ccAddresses = cc.build(); if (!ccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()])); } List<InternetAddress> bccAddresses = bcc.build(); if (!bccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(new InternetAddress[bccAddresses.size()])); } MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage); List<Header> headerList = headers.build(); for (Header header : headerList) { if (header.name.equals("Message-ID") || header.name.equals("Date")) { wrappedMessage.setHeader(header.name, header.value); } else { wrappedMessage.addHeader(header.name, header.value); } } wrappedMessage.saveChanges(); return wrappedMessage; }
From source file:com.trivago.mail.pigeon.mail.MailFacade.java
public void sendMail(MailTransport mailTransport) { log.debug("Mail delivery started"); File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile(); Properties config = new Properties(); try {// w w w. j a v a 2 s . co m config.load(new FileReader(propertyfile)); } catch (IOException e) { log.error(e); } Session session = Session.getDefaultInstance(config); log.debug("Received session"); MimeMessage message = new MimeMessage(session); String to = mailTransport.getTo(); String from = mailTransport.getFrom(); String replyTo = mailTransport.getReplyTo(); String subject = mailTransport.getSubject(); String html = mailTransport.getHtml(); String text = mailTransport.getText(); try { Address fromAdr = new InternetAddress(from); Address toAdr = new InternetAddress(to); Address rplyAdr = new InternetAddress(replyTo); message.setSubject(subject); message.setFrom(fromAdr); message.setRecipient(Message.RecipientType.TO, toAdr); message.setReplyTo(new Address[] { rplyAdr }); message.setSender(fromAdr); message.addHeader("Return-path", replyTo); message.addHeader("X-TRV-MID", mailTransport.getmId()); message.addHeader("X-TRV-UID", mailTransport.getuId()); // Content MimeBodyPart messageTextPart = new MimeBodyPart(); messageTextPart.setText(text); messageTextPart.setContent(html, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageTextPart); // Put parts in message message.setContent(multipart); log.debug("Dispatching message"); Transport.send(message); log.debug("Mail delivery ended"); } catch (MessagingException e) { log.error(e); } }
From source file:org.eurekastreams.server.action.execution.notification.email.SendNotificationEmailExecution.java
/** * {@inheritDoc}/* w w w.j a v a 2 s . c om*/ */ @Override public Serializable execute(final ActionContext inActionContext) throws ExecutionException { NotificationEmailDTO request = (NotificationEmailDTO) inActionContext.getParams(); try { MimeMessage message = emailer.createMessage(); emailer.setSubject(message, request.getSubject()); emailer.setTextBody(message, request.getTextBody()); if (StringUtils.isNotBlank(request.getHtmlBody())) { emailer.setHtmlBody(message, request.getHtmlBody()); } if (StringUtils.isNotBlank(request.getToRecipient())) { emailer.setTo(message, request.getToRecipient()); } if (StringUtils.isNotBlank(request.getBccRecipients())) { emailer.setBcc(message, request.getBccRecipients()); } if (StringUtils.isNotBlank(request.getReplyTo())) { emailer.setReplyTo(message, request.getReplyTo()); } if (request.isHighPriority()) { message.addHeader("Importance", "high"); message.addHeader("X-Priority", "1"); } emailer.sendMail(message); log.debug("Sent email for notification {}", request.getDescription()); } catch (MessagingException ex) { String msg = "Failed to send email message for notification " + request.getDescription(); log.error(msg, ex); throw new ExecutionException(msg, ex); } return null; }
From source file:it.geosolutions.geobatch.mail.SendMailAction.java
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { final Queue<EventObject> ret = new LinkedList<EventObject>(); while (events.size() > 0) { final EventObject ev; try {/*from ww w . ja v a 2 s .c o m*/ if ((ev = events.remove()) != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource()); } File mail = (File) ev.getSource(); FileInputStream fis = new FileInputStream(mail); String kmlURL = IOUtils.toString(fis); // ///////////////////////////////////////////// // Send the mail with the given KML URL // ///////////////////////////////////////////// // Recipient's email ID needs to be mentioned. String mailTo = conf.getMailToAddress(); // Sender's email ID needs to be mentioned String mailFrom = conf.getMailFromAddress(); // Get system properties Properties properties = new Properties(); // Setup mail server String mailSmtpAuth = conf.getMailSmtpAuth(); properties.put("mail.smtp.auth", mailSmtpAuth); properties.put("mail.smtp.host", conf.getMailSmtpHost()); properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable()); properties.put("mail.smtp.port", conf.getMailSmtpPort()); // Get the default Session object. final String mailAuthUsername = conf.getMailAuthUsername(); final String mailAuthPassword = conf.getMailAuthPassword(); Session session = Session.getDefaultInstance(properties, (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailAuthUsername, mailAuthPassword); } } : null)); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(mailFrom)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); // Set Subject: header field message.setSubject(conf.getMailSubject()); String mailHeaderName = conf.getMailHeaderName(); String mailHeaderValule = conf.getMailHeaderValue(); if (mailHeaderName != null && mailHeaderValule != null) { message.addHeader(mailHeaderName, mailHeaderValule); } String mailMessageText = conf.getMailContentHeader(); message.setText(mailMessageText + "\n\n" + kmlURL); // Send message Transport.send(message); if (LOGGER.isInfoEnabled()) LOGGER.info("Sent message successfully...."); } catch (MessagingException exc) { ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ..."); continue; } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING..."); } continue; } } catch (Exception ioe) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Send Mail action.execute(): Unable to produce the output: ", ioe.getLocalizedMessage(), ioe); } throw new ActionException(this, ioe.getLocalizedMessage(), ioe); } } return ret; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Create basic Message which contains all headers. No body is filled * * @param session the Session//from w w w . j a v a 2s. c om * @param action the action * @return message * @throws AddressException * @throws MessagingException */ public Message createMessage(Session session, SendMessageAction action) throws AddressException, MessagingException { MimeMessage message = new MimeMessage(session); SmtpMessage m = action.getMessage(); message.setFrom(new InternetAddress(m.getFrom())); userPreferences.addContact(m.getTo()); userPreferences.addContact(m.getCc()); userPreferences.addContact(m.getBcc()); message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo())); message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc())); message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc())); message.setSentDate(new Date()); message.addHeader("User-Agent:", "HUPA, The Apache JAMES webmail client."); message.addHeader("X-Originating-IP", getClientIpAddr()); message.setSubject(m.getSubject(), "utf-8"); updateHeaders(message, action); message.saveChanges(); 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 www .j a v a 2 s . 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:com.duroty.service.Mailet.java
/** * DOCUMENT ME!/*from w ww.j a v a 2 s . c om*/ * * @param id DOCUMENT ME! * @param message DOCUMENT ME! */ private void saveInReplyTo(String id, MimeMessage message) { try { String[] inReplyTos = message.getHeader(RFC2822Headers.IN_REPLY_TO); String messageId = message.getMessageID(); if ((inReplyTos == null) || (inReplyTos.length <= 0)) { if (messageId != null) { message.addHeader(RFC2822Headers.IN_REPLY_TO, messageId); message.saveChanges(); } } String[] references = message.getHeader(RFC2822Headers.REFERENCES); if ((references == null) || (references.length <= 0)) { message.addHeader(RFC2822Headers.REFERENCES, messageId); message.saveChanges(); } } catch (Exception e) { } }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public void sendMail(String from, String to, String subject, String messageText, Map<Object, Object> extraHeaders) { try {/*from w w w .j a v a2 s .c o m*/ MimeMessage msg = new MimeMessage(session); if (from.matches(EMAIL_PATTERN)) { msg.setFrom(new InternetAddress(from)); } else { // set fake from address; instead, add it as part of the message //msg.setFrom(new InternetAddress("invalid.email.address@mailinator.com")); msg.setFrom(getSystemAddress()); messageText = "From: " + from + "\n\n" + messageText; } msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject, charset); msg.setText(messageText, charset); if (extraHeaders != null) { for (Object key : extraHeaders.keySet()) { String headerName = key.toString(); String headerValue = extraHeaders.get(key).toString(); msg.addHeader(headerName, headerValue); } } Transport.send(msg); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } }
From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java
/** * Delivers a mail to a local mailbox.// w ww. j a v a2s .c o m * * @param mail * the mail being processed * * @throws MessagingException * if an error occurs while storing the mail */ @SuppressWarnings("unchecked") @Override public void service(Mail mail) throws MessagingException { Collection<MailAddress> recipients = mail.getRecipients(); Collection<MailAddress> errors = new Vector<MailAddress>(); MimeMessage message = null; if (deliveryHeader != null || resetReturnPath) { message = mail.getMessage(); } if (resetReturnPath) { // Set Return-Path and remove all other Return-Path headers from the // message // This only works because there is a placeholder inserted by // MimeMessageWrapper message.setHeader(RFC2822Headers.RETURN_PATH, (mail.getSender() == null ? "<>" : "<" + mail.getSender() + ">")); } Enumeration headers; InternetHeaders deliveredTo = new InternetHeaders(); if (deliveryHeader != null) { // Copy any Delivered-To headers from the message headers = message.getMatchingHeaders(new String[] { deliveryHeader }); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); deliveredTo.addHeader(header.getName(), header.getValue()); } } for (Iterator<MailAddress> i = recipients.iterator(); i.hasNext();) { MailAddress recipient = i.next(); try { if (deliveryHeader != null) { // Add qmail's de facto standard Delivered-To header message.addHeader(deliveryHeader, recipient.toString()); } storeMail(mail.getSender(), recipient, mail); if (deliveryHeader != null) { if (i.hasNext()) { // Remove headers but leave all placeholders message.removeHeader(deliveryHeader); headers = deliveredTo.getAllHeaders(); // And restore any original Delivered-To headers while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); message.addHeader(header.getName(), header.getValue()); } } } } catch (Exception ex) { log("Error while storing mail.", ex); errors.add(recipient); } } if (!errors.isEmpty()) { // If there were errors, we redirect the email to the ERROR // processor. // In order for this server to meet the requirements of the SMTP // specification, mails on the ERROR processor must be returned to // the sender. Note that this email doesn't include any details // regarding the details of the failure(s). // In the future we may wish to address this. getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(), Mail.ERROR); } if (consume) { // Consume this message mail.setState(Mail.GHOST); } }
From source file:org.apache.mailet.base.test.MimeMessageBuilder.java
public MimeMessage build() throws MessagingException { Preconditions.checkState(!(text.isPresent() && content.isPresent()), "Can not get at the same time a text and a content"); MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties())); if (text.isPresent()) { BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text.get());//ww w. jav a 2 s.c om mimeMessage.setContent(bodyPart, "text/plain"); } if (content.isPresent()) { mimeMessage.setContent(content.get()); } if (sender.isPresent()) { mimeMessage.setSender(sender.get()); } if (from.isPresent()) { mimeMessage.setFrom(from.get()); } if (subject.isPresent()) { mimeMessage.setSubject(subject.get()); } List<InternetAddress> toAddresses = to.build(); if (!toAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[toAddresses.size()])); } List<InternetAddress> ccAddresses = cc.build(); if (!ccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()])); } List<InternetAddress> bccAddresses = bcc.build(); if (!bccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(new InternetAddress[bccAddresses.size()])); } List<Header> headerList = headers.build(); for (Header header : headerList) { mimeMessage.addHeader(header.name, header.value); } mimeMessage.saveChanges(); return mimeMessage; }