List of usage examples for javax.mail.internet MimeMessage addHeader
@Override public void addHeader(String name, String value) throws MessagingException
From source file:nl.surfnet.coin.teams.control.AddMemberController.java
/** * Sends an email based on the {@link Invitation} * * @param invitation {@link Invitation} that contains the necessary data * @param subject of the email//from w w w.j a v a 2s .c o m * @param inviter {@link Person} who sends the invitation * @param locale {@link Locale} for the mail */ protected void sendInvitationByMail(final Invitation invitation, final String subject, final Person inviter, final Locale locale) { final String html = composeInvitationMailMessage(invitation, inviter, locale, "html"); final String plainText = composeInvitationMailMessage(invitation, inviter, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(invitation.getEmail())); mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java
public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException { log.trace("marshal(ShsMessage, OutputStream)"); MimeMultipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); try {/*from w ww. j av a 2 s. co m*/ ShsLabel label = shsMessage.getLabel(); if (label == null) { throw new IllegalMessageStructureException("label not found in shs message"); } Content content = label.getContent(); if (content == null) { throw new IllegalMessageStructureException("label/content not found in shs label"); } else { // we will update this according to our data parts below. content.getDataOrCompound().clear(); String contentId = content.getContentId(); content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID))); } List<DataPart> dataParts = shsMessage.getDataParts(); if (dataParts.isEmpty()) { throw new IllegalMessageStructureException("dataparts not found in message"); } for (DataPart dp : dataParts) { Data data = new Data(); data.setDatapartType(dp.getDataPartType()); data.setFilename(dp.getFileName()); if (dp.getContentLength() != null && dp.getContentLength() > 0) data.setNoOfBytes("" + dp.getContentLength()); content.getDataOrCompound().add(data); } bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1"); bodyPart.setHeader("Content-Transfer-Encoding", "binary"); multipart.addBodyPart(bodyPart); for (DataPart dataPart : dataParts) { bodyPart = new MimeBodyPart(); bodyPart.setDisposition(Part.ATTACHMENT); if (StringUtils.isNotBlank(dataPart.getFileName())) { bodyPart.setFileName(dataPart.getFileName()); } bodyPart.setDataHandler(dataPart.getDataHandler()); if (dataPart.getTransferEncoding() != null) { bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase()); } multipart.addBodyPart(bodyPart); } MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject("SHS Message"); mimeMessage.addHeader("Content-Transfer-Encoding", "binary"); mimeMessage.setContent(multipart); mimeMessage.saveChanges(); String ignoreList[] = { "Message-ID" }; mimeMessage.writeTo(outputStream, ignoreList); outputStream.flush(); } catch (Exception e) { if (e instanceof IllegalMessageStructureException) { throw (IllegalMessageStructureException) e; } throw new IllegalMessageStructureException(e); } }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
protected void updateHeaders(MimeMessage message, SendMessageAction action) { if (action.getInReplyTo() != null) { try {/* ww w . j a va 2 s . c o m*/ message.addHeader(SConsts.HEADER_IN_REPLY_TO, action.getInReplyTo()); } catch (MessagingException e) { logger.error("Error while setting header:" + e.getMessage(), e); } } if (action.getReferences() != null) { try { message.addHeader(SConsts.HEADER_REFERENCES, action.getReferences()); } catch (MessagingException e) { logger.error("Error while setting header:" + e.getMessage(), e); } } }
From source file:davmail.smtp.TestSmtp.java
public void sendAndCheckMessage(MimeMessage mimeMessage, String from, String bcc) throws IOException, MessagingException, InterruptedException { // generate message id mimeMessage.saveChanges();/*from www. java2 s.c om*/ // mimeMessage.writeTo(System.out); // copy Message-id to references header mimeMessage.addHeader("references", mimeMessage.getHeader("message-id")[0]); if (from != null) { writeLine("MAIL FROM:" + from); } else { writeLine("MAIL FROM:" + session.getEmail()); } readLine(); if (bcc != null) { writeLine("RCPT TO:" + bcc); readLine(); } writeLine("RCPT TO:" + Settings.getProperty("davmail.to")); readLine(); writeLine("DATA"); assertEquals("354 Start mail input; end with <CRLF>.<CRLF>", readLine()); mimeMessage.writeTo(new DoubleDotOutputStream(socketOutputStream)); writeLine(""); writeLine("."); assertEquals("250 Queued mail for delivery", readLine()); // wait for asynchronous message send ExchangeSession.MessageList messages = null; for (int i = 0; i < 5; i++) { messages = session.searchMessages("Sent", session.headerIsEqualTo("references", mimeMessage.getMessageID())); if (messages.size() > 0) { break; } Thread.sleep(1000); } assertEquals(1, messages.size()); ExchangeSession.Message sentMessage = messages.get(0); sentMessage.getMimeMessage().writeTo(System.out); assertEquals(mimeMessage.getDataHandler().getContent(), sentMessage.getMimeMessage().getDataHandler().getContent()); }
From source file:com.haulmont.cuba.core.app.EmailSender.java
private void addHeaders(SendingMessage sendingMessage, MimeMessage message) throws MessagingException { if (sendingMessage.getHeaders() == null) return;// w w w . j a va 2 s . c o m String[] splitHeaders = sendingMessage.getHeaders().split(SendingMessage.HEADERS_SEPARATOR); for (String header : splitHeaders) { EmailHeader emailHeader = EmailHeader.parse(header); if (emailHeader != null) { message.addHeader(emailHeader.getName(), emailHeader.getValue()); } else { log.warn("Can't parse email header: '{}'", header); } } }
From source file:com.mobileman.projecth.business.impl.MailManagerImpl.java
/** * @param mimeMessage/*from www . j a v a 2 s. c o m*/ * @throws MessagingException */ private void prepareMessage(MimeMessage mimeMessage) throws MessagingException { if (log.isDebugEnabled()) { log.debug("prepareMessage(MimeMessage) - start"); //$NON-NLS-1$ } mimeMessage.addHeader("Content-Type", "text/plain;charset=UTF-8"); mimeMessage.setSentDate(new Date()); if (log.isDebugEnabled()) { log.debug("prepareMessage(MimeMessage) - returns"); //$NON-NLS-1$ } }
From source file:hudson.tasks.MailSender.java
private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException, UnsupportedEncodingException { MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession()); // TODO: I'd like to put the URL to the page in here, // but how do I obtain that? msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName()); msg.addHeader("X-Jenkins-Result", build.getResult().toString()); msg.setContent("", "text/plain"); msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset)); msg.setSentDate(new Date()); String replyTo = Mailer.descriptor().getReplyToAddress(); if (StringUtils.isNotBlank(replyTo)) { msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) }); }//from ww w .ja v a2 s . c om Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>(); String defaultSuffix = Mailer.descriptor().getDefaultSuffix(); StringTokenizer tokens = new StringTokenizer(recipients); while (tokens.hasMoreTokens()) { String address = tokens.nextToken(); if (address.startsWith("upstream-individuals:")) { // people who made a change in the upstream String projectName = address.substring("upstream-individuals:".length()); AbstractProject up = Jenkins.getInstance().getItem(projectName, build.getProject(), AbstractProject.class); if (up == null) { listener.getLogger().println("No such project exist: " + projectName); continue; } includeCulpritsOf(up, build, listener, rcp); } else { // ordinary address // if not a valid address (i.e. no '@'), then try adding suffix if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) { address += defaultSuffix; } try { rcp.add(Mailer.StringToAddress(address, charset)); } catch (AddressException e) { // report bad address, but try to send to other addresses listener.getLogger().println("Unable to send to address: " + address); e.printStackTrace(listener.error(e.getMessage())); } } } for (AbstractProject project : includeUpstreamCommitters) { includeCulpritsOf(project, build, listener, rcp); } if (sendToIndividuals) { Set<User> culprits = build.getCulprits(); if (debug) listener.getLogger() .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)==" + culprits.size()); rcp.addAll(buildCulpritList(listener, culprits)); } msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()])); AbstractBuild<?, ?> pb = build.getPreviousBuild(); if (pb != null) { MailMessageIdAction b = pb.getAction(MailMessageIdAction.class); if (b != null) { msg.setHeader("In-Reply-To", b.messageId); msg.setHeader("References", b.messageId); } } return msg; }
From source file:nl.surfnet.coin.teams.control.DetailTeamController.java
/** * Notifies the user that requested to join a team that his request has been * declined//from w ww . j a va2 s . com * * @param memberToAdd {@link Person} that wanted to join the team * @param team {@link Team} he wanted to join * @param locale {@link Locale} */ private void sendDeclineMail(final Person memberToAdd, final Team team, final Locale locale) { final String subject = messageSource.getMessage("request.mail.declined.subject", null, locale); final String html = composeDeclineMailMessage(team, locale, "html"); final String plainText = composeDeclineMailMessage(team, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:nl.surfnet.coin.teams.control.DetailTeamController.java
/** * Notifies the user that requested to join a team that his request has been * declined/*from w w w .j a va 2 s. c o m*/ * * @param memberToAdd {@link Person} that wanted to join the team * @param team {@link Team} he wanted to join * @param locale {@link Locale} */ private void sendAcceptMail(final Person memberToAdd, final Team team, final Locale locale) { final String subject = messageSource.getMessage("request.mail.accepted.subject", null, locale); final String html = composeAcceptMailMessage(team, locale, "html"); final String plainText = composeAcceptMailMessage(team, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:org.apache.axis.transport.mail.MailSender.java
/** * Send the soap request message to the server * * @param msgContext message context/* ww w .ja v a2s.c o m*/ * * @return id for the current message * @throws Exception */ private String writeUsingSMTP(MessageContext msgContext) throws Exception { String id = (new java.rmi.server.UID()).toString(); String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST); SMTPClient client = new SMTPClient(); client.connect(smtpHost); // After connection attempt, you should check the reply code to verify // success. System.out.print(client.getReplyString()); int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } client.login(smtpHost); System.out.print(client.getReplyString()); reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS); String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress)); // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message reqMessage = msgContext.getRequestMessage(); msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")); msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action); msg.setDisposition(MimePart.INLINE); msg.setSubject(id); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); reqMessage.writeTo(out); msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(fromAddress); System.out.print(client.getReplyString()); client.addRecipient(toAddress); System.out.print(client.getReplyString()); Writer writer = client.sendMessageData(); System.out.print(client.getReplyString()); writer.write(out2.toString()); writer.flush(); writer.close(); System.out.print(client.getReplyString()); if (!client.completePendingCommand()) { System.out.print(client.getReplyString()); AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null); throw fault; } System.out.print(client.getReplyString()); client.logout(); client.disconnect(); return id; }