List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Multipart mp) throws MessagingException
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Sends a mail message. The content must be provided as MimeBodyPart objects. * * @param from Sender's email address. * @param to Recipient's email address. * @param cc Email address for CC. * @param bcc Email address for BCC. * @param subject Subject text for the email. * @param bodyParts The body parts to insert into the message. * @throws SystemException if an unexpected error occurs. * @throws ConfigurationException if a configuration error occurs. *///www . ja va2 s . co m public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts) throws ConfigurationException, SystemException { initEventLog(); try { Properties props = new Properties(); Configuration config = Aksess.getConfiguration(); String host = config.getString("mail.host"); if (host == null) { throw new ConfigurationException("mail.host"); } // I noen tilfeller nsker vi at all epost skal g til en testadresse String catchAllTo = config.getString("mail.catchall.to"); boolean catchallExists = catchAllTo != null && catchAllTo.contains("@"); if (catchallExists) { StringBuilder prefix = new StringBuilder(" (original recipient: " + to); if (cc != null) { prefix.append(", cc: ").append(cc); } if (bcc != null) { prefix.append(", bcc: ").append(bcc); } prefix.append(") "); subject = prefix + subject; to = catchAllTo; cc = null; bcc = null; } props.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(props); boolean debug = config.getBoolean("mail.debug", false); if (debug) { session.setDebug(true); } // Opprett message, sett attributter MimeMessage message = new MimeMessage(session); InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddress[] = InternetAddress.parse(to); message.setFrom(fromAddress); if (toAddress.length > 1) { message.setRecipients(Message.RecipientType.BCC, toAddress); } else { message.setRecipients(Message.RecipientType.TO, toAddress); } if (cc != null) { message.addRecipients(Message.RecipientType.CC, cc); } if (bcc != null) { message.addRecipients(Message.RecipientType.BCC, bcc); } message.setSubject(subject, "ISO-8859-1"); message.setSentDate(new Date()); Multipart mp = new MimeMultipart(); for (MimeBodyPart bodyPart : bodyParts) { mp.addBodyPart(bodyPart); } message.setContent(mp); // Send meldingen Transport.send(message); eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null); // Logg sending log.info("Sending email to " + to + " with subject " + subject); } catch (MessagingException e) { String errormessage = "Subject: " + subject + " | Error: " + e.getMessage(); eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null); log.error("Error sending mail", e); throw new SystemException("Error sending email to : " + to + " with subject " + subject, e); } }
From source file:com.basicservice.service.MailService.java
public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception { try {//ww w . j ava 2 s. co m Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", 587); props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(); Session mailSession = Session.getDefaultInstance(props, auth); // mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); Multipart multipart = new MimeMultipart("alternative"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); message.setFrom(new InternetAddress(from)); message.setSubject(subject, "UTF-8"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); transport.connect(); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } catch (Exception e) { LOG.debug("Exception while sending email: ", e); throw e; } }
From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java
public static ParsedMessage generateMessageWithAttachment(String subject) throws Exception { MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession()); mm.setHeader("From", "Vera Oliphant <oli@example.com>"); mm.setHeader("To", "Jimmy Dean <jdean@example.com>"); mm.setHeader("Subject", subject); mm.setText("Good as gold"); MimeMultipart multi = new ZMimeMultipart("mixed"); ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT); cdisp.setParameter("filename", "fun.txt"); ZMimeBodyPart bp = new ZMimeBodyPart(); // MimeBodyPart.setDataHandler() invalidates Content-Type and CTE if there is any, so make sure // it gets called before setting Content-Type and CTE headers. try {/*w w w .ja v a 2s . com*/ bp.setDataHandler(new DataHandler(new ByteArrayDataSource("Feeling attached.", "text/plain"))); } catch (IOException e) { throw new MessagingException("could not generate mime part content", e); } bp.addHeader("Content-Disposition", cdisp.toString()); bp.addHeader("Content-Type", "text/plain"); bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT); multi.addBodyPart(bp); mm.setContent(multi); mm.saveChanges(); return new ParsedMessage(mm, false); }
From source file:de.elomagic.mag.AbstractTest.java
protected MimeMessage createMimeMessage(String filename) throws Exception { MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("This is some text to be displayed inline", "text/plain"); textPart.setDisposition(Part.INLINE); MimeBodyPart binaryPart = new MimeBodyPart(); InputStream in = getClass().getResourceAsStream("/TestFile.pdf"); binaryPart.setContent(getOriginalMailAttachment(), "application/pdf"); binaryPart.setDisposition(Part.ATTACHMENT); binaryPart.setFileName(filename);/*from w w w . jav a 2s . c o m*/ Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(binaryPart); MimeMessage message = new MimeMessage(greenMail.getImap().createSession()); message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("mailuser@localhost.com") }); message.setSubject("Another test mail subject"); message.setContent(mp); // return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup()); }
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 ww w . java 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.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); newMessage.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); return newMessage; }
From source file:net.sourceforge.subsonic.backend.service.EmailSession.java
public void sendHtmlMessage(String from, List<String> to, List<String> cc, List<String> bcc, List<String> replyTo, String subject, String html, String plain) throws MessagingException { MimeMessage message = createMessage(from, to, cc, bcc, replyTo, subject); MimeBodyPart plainPart = new MimeBodyPart(); plainPart.setText(plain);/*from w w w . j av a 2 s .c om*/ MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setText(html, "utf-8", "html"); MimeMultipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(plainPart); multipart.addBodyPart(htmlPart); message.setContent(multipart); sendMessage(message); }
From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java
private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content) throws ConfigurationException { try {/*from w w w. jav a 2 s . c o m*/ log.debug("Sending mail."); MiscUtil.assertNotNull(subject, "subject"); MiscUtil.assertNotNull(recipient, "recipient"); MiscUtil.assertNotNull(content, "content"); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", config.getSMTPMailHost()); log.trace("Mail host: " + config.getSMTPMailHost()); if (config.getSMTPMailPort() != null) { log.trace("Mail port: " + config.getSMTPMailPort()); props.setProperty("mail.port", config.getSMTPMailPort()); } if (config.getSMTPMailUsername() != null) { log.trace("Mail user: " + config.getSMTPMailUsername()); props.setProperty("mail.user", config.getSMTPMailUsername()); } if (config.getSMTPMailPassword() != null) { log.trace("Mail password: " + config.getSMTPMailPassword()); props.setProperty("mail.password", config.getSMTPMailPassword()); } Session mailSession = Session.getDefaultInstance(props, null); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject); log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress()); message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName())); log.trace("Recipient: " + recipient); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); log.trace("Creating multipart content of mail."); MimeMultipart multipart = new MimeMultipart("related"); log.trace("Adding first part (html)"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15"); multipart.addBodyPart(messageBodyPart); // log.trace("Adding mail images"); // messageBodyPart = new MimeBodyPart(); // for (Image image : images) { // messageBodyPart.setDataHandler(new DataHandler(image)); // messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">"); // multipart.addBodyPart(messageBodyPart); // } message.setContent(multipart); transport.connect(); log.trace("Sending mail message."); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); log.trace("Successfully sent."); transport.close(); } catch (MessagingException e) { throw new ConfigurationException(e); } catch (UnsupportedEncodingException e) { throw new ConfigurationException(e); } }
From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void onMessage(Message arg0) { ObjectMessage objectMessage = (ObjectMessage) arg0; try {/*from w w w. ja v a 2 s .c o m*/ Mail mail = (Mail) objectMessage.getObject(); // Get properties String mailProtocol = getMailProtocol(); String mailServer = getSmtpServer(); String mailUser = getSmtpUser(); String mailPort = getSmtpPort(); String mailPassword = getSmtpPassword(); // Initialize a mail session Properties props = new Properties(); props.put("mail." + mailProtocol + ".host", mailServer); props.put("mail." + mailProtocol + ".port", mailPort); Session session = Session.getInstance(props); // Create the message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mail.getSender())); for (String recipient : mail.getRecipients()) { msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } msg.setSubject(mail.getSubject(), "UTF-8"); Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // Set the email message text and attachment MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setContent(mail.getBody(), mail.getContentType()); multipart.addBodyPart(messagePart); if (mail.getAttachmentData() != null) { ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(), mail.getAttachmentContentType()); DataHandler dataHandler = new DataHandler(byteArrayDataSource); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(mail.getAttachmentFileName()); multipart.addBodyPart(attachmentPart); } // Open transport and send message Transport transport = session.getTransport(mailProtocol); if (StringUtils.isNotBlank(mailUser)) { transport.connect(mailUser, mailPassword); } else { transport.connect(); } msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); } catch (JMSException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e); throw new RuntimeException(e); } catch (MessagingException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e); throw new RuntimeException(e); } }