List of usage examples for javax.mail.internet MimeMessage setHeader
@Override public void setHeader(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)); }//from w w w.j av a 2 s . c o m 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:org.apache.james.James.java
/** * Generates a bounce mail that is a bounce of the original message. * * @param bounceText the text to be prepended to the message to describe the bounce condition * * @return the bounce mail/* ww w .j av a 2 s . co m*/ * * @throws MessagingException if the bounce mail could not be created */ private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException { //This sends a message to the james component that is a bounce of the sent message MimeMessage original = mail.getMessage(); MimeMessage reply = (MimeMessage) original.reply(false); reply.setSubject("Re: " + original.getSubject()); reply.setSentDate(new Date()); Collection recipients = new HashSet(); recipients.add(mail.getSender()); InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) }; reply.setRecipients(Message.RecipientType.TO, addr); reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString())); reply.setText(bounceText); reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName()); return new MailImpl("replyTo-" + mail.getName(), new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply); }
From source file:org.apache.james.mailetcontainer.impl.JamesMailetContext.java
/** * Generates a bounce mail that is a bounce of the original message. * * @param bounceText the text to be prepended to the message to describe the bounce * condition//from w w w . j a va2 s. c o m * @return the bounce mail * @throws MessagingException if the bounce mail could not be created */ private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException { // This sends a message to the james component that is a bounce of the // sent message MimeMessage original = mail.getMessage(); MimeMessage reply = (MimeMessage) original.reply(false); reply.setSubject("Re: " + original.getSubject()); reply.setSentDate(new Date()); Collection<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(mail.getSender()); InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) }; reply.setRecipients(Message.RecipientType.TO, addr); reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString())); reply.setText(bounceText); reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName()); return new MailImpl("replyTo-" + mail.getName(), new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply); }
From source file:org.apache.james.smtpserver.SetMimeHeaderHandler.java
/** * Adds header to the message// w w w. ja v a 2 s . co m * * @see org.apache.james.smtpserver.JamesMessageHook#onMessage(org.apache.james.protocols.smtp.SMTPSession, * org.apache.mailet.Mail) */ public HookResult onMessage(SMTPSession session, Mail mail) { try { MimeMessage message = mail.getMessage(); // Set the header name and value (supplied at init time). if (headerName != null) { message.setHeader(headerName, headerValue); message.saveChanges(); } } catch (javax.mail.MessagingException me) { session.getLogger().error(me.getMessage()); } return new HookResult(HookReturnCode.DECLINED); }
From source file:org.apache.james.transport.mailets.delivery.MailDispatcher.java
private Collection<MailAddress> customizeHeadersAndDeliver(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); // 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, DeliveryUtils.prettyPrint(mail.getSender())); List<String> deliveredToHeader = removeDeliveryHeaders(message); Collection<MailAddress> errors = deliver(mail, message); putDeliveryHeadersBack(message, deliveredToHeader); return errors; }
From source file:org.apache.james.transport.mailets.DSNBounce.java
private MimeMessage createBounceMessage(Mail originalMail) throws MessagingException { MimeMultipartReport multipart = createMultipart(originalMail); MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); newMessage.setContent(multipart);//from w ww . j ava2s.c o m newMessage.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); return newMessage; }
From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java
/** * Delivers a mail to a local mailbox.//from w ww . j av a 2 s .com * * @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.jsieve.mailet.SieveMailboxMailet.java
/** * Deliver the original mail as an attachment with the main part being an error report. * * @param recipient//from w w w. ja va 2s. c o m * @param aMail * @param ex * @throws MessagingException * @throws IOException */ protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex) throws MessagingException, IOException { String user = getUsername(recipient); MimeMessage originalMessage = aMail.getMessage(); MimeMessage message = new MimeMessage(originalMessage); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart noticePart = new MimeBodyPart(); noticePart.setText(new StringBuilder().append( "An error was encountered while processing this mail with the active sieve script for user \"") .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage()) .append("\r\n").toString()); multipart.addBodyPart(noticePart); MimeBodyPart originalPart = new MimeBodyPart(); originalPart.setContent(originalMessage, "message/rfc822"); if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) { originalPart.setFileName(originalMessage.getSubject().trim()); } else { originalPart.setFileName("No Subject"); } originalPart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(originalPart); message.setContent(multipart); message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject()); message.setHeader("X-Priority", "1"); message.saveChanges(); storeMessageInbox(user, message); }
From source file:org.asqatasun.emailsender.EmailSender.java
/** * * @param emailFrom// www . j av a 2s .co m * @param emailToSet * @param emailBccSet (can be null) * @param replyTo (can be null) * @param emailSubject * @param emailContent */ public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // create some properties and get the default Session Session session = Session.getInstance(props); session.setDebug(debug); try { Transport t = session.getTransport("smtp"); t.connect(smtpHost, userName, password); // create a message MimeMessage msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom; try { // Used default from address is passed one is null or empty or // blank addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from); msg.setFrom(addressFrom); Address[] recipients = new InternetAddress[emailToSet.size()]; int i = 0; for (String emailTo : emailToSet) { recipients[i] = new InternetAddress(emailTo); i++; } msg.setRecipients(Message.RecipientType.TO, recipients); if (CollectionUtils.isNotEmpty(emailBccSet)) { Address[] bccRecipients = new InternetAddress[emailBccSet.size()]; i = 0; for (String emailBcc : emailBccSet) { bccRecipients[i] = new InternetAddress(emailBcc); i++; } msg.setRecipients(Message.RecipientType.BCC, bccRecipients); } if (StringUtils.isNotBlank(replyTo)) { Address[] replyToRecipients = { new InternetAddress(replyTo) }; msg.setReplyTo(replyToRecipients); } // Setting the Subject msg.setSubject(emailSubject, CHARSET_KEY); // Setting content and charset (warning: both declarations of // charset are needed) msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY); LOGGER.debug("emailContent " + emailContent); msg.setContent(emailContent, FULL_CHARSET_KEY); try { LOGGER.debug("emailContent from message object " + msg.getContent().toString()); } catch (IOException ex) { LOGGER.error(ex.getMessage()); } catch (MessagingException ex) { LOGGER.error(ex.getMessage()); } for (Address addr : msg.getAllRecipients()) { LOGGER.debug("addr " + addr); } t.sendMessage(msg, msg.getAllRecipients()); } catch (AddressException ex) { LOGGER.warn("AddressException " + ex.getMessage()); LOGGER.warn("AddressException " + ex.getStackTrace()); } } catch (NoSuchProviderException e) { LOGGER.warn("NoSuchProviderException " + e.getMessage()); LOGGER.warn("NoSuchProviderException " + e.getStackTrace()); } catch (MessagingException e) { LOGGER.warn("MessagingException " + e.getMessage()); LOGGER.warn("MessagingException " + e.getStackTrace()); } }
From source file:org.chiba.connectors.smtp.SMTPSubmissionHandler.java
private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception { URL url = new URL(uri); String recipient = url.getPath(); String server = null;/*from ww w . jav a 2s. co m*/ String port = null; String sender = null; String subject = null; String username = null; String password = null; StringTokenizer headers = new StringTokenizer(url.getQuery(), "&"); while (headers.hasMoreTokens()) { String token = headers.nextToken(); if (token.startsWith("server=")) { server = URLDecoder.decode(token.substring("server=".length())); continue; } if (token.startsWith("port=")) { port = URLDecoder.decode(token.substring("port=".length())); continue; } if (token.startsWith("sender=")) { sender = URLDecoder.decode(token.substring("sender=".length())); continue; } if (token.startsWith("subject=")) { subject = URLDecoder.decode(token.substring("subject=".length())); continue; } if (token.startsWith("username=")) { username = URLDecoder.decode(token.substring("username=".length())); continue; } if (token.startsWith("password=")) { password = URLDecoder.decode(token.substring("password=".length())); continue; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("smtp server '" + server + "'"); if (username != null) { LOGGER.debug("smtp-auth username '" + username + "'"); } LOGGER.debug("mail sender '" + sender + "'"); LOGGER.debug("subject line '" + subject + "'"); } Properties properties = System.getProperties(); properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled())); properties.put("mail.smtp.from", sender); properties.put("mail.smtp.host", server); if (port != null) { properties.put("mail.smtp.port", port); } if (username != null) { properties.put("mail.smtp.auth", String.valueOf(true)); properties.put("mail.smtp.user", username); } Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password)); MimeMessage message = null; if (mediatype.startsWith("multipart/")) { message = new MimeMessage(session, new ByteArrayInputStream(data)); } else { message = new MimeMessage(session); if (mediatype.toLowerCase().indexOf("charset=") == -1) { mediatype += "; charset=\"" + encoding + "\""; } message.setText(new String(data, encoding), encoding); message.setHeader("Content-Type", mediatype); } message.setRecipient(RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setSentDate(new Date()); Transport.send(message); }