Java Code Examples for javax.mail.internet.MimeBodyPart#setContent()
The following examples show how to use
javax.mail.internet.MimeBodyPart#setContent() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailTestUtil.java From camunda-bpm-mail with Apache License 2.0 | 6 votes |
public static MimeMessage createMimeMessageWithHtml(Session session) throws MessagingException, AddressException { MimeMessage message = createMimeMessage(session); Multipart multiPart = new MimeMultipart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("text"); multiPart.addBodyPart(textPart); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<b>html</b>", MailContentType.TEXT_HTML.getType()); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); return message; }
Example 2
Source File: DSNBounce.java From james-project with Apache License 2.0 | 6 votes |
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); MimeMessage originalMessage = originalMail.getMessage(); if (attachmentType.equals(TypeCode.HEADS)) { part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain"); part.setHeader("Content-Type", "text/rfc822-headers"); } else { part.setContent(originalMessage, "message/rfc822"); } if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) { part.setFileName(originalMessage.getSubject().trim()); } else { part.setFileName("No Subject"); } part.setDisposition("Attachment"); return part; }
Example 3
Source File: MainAppExample.java From javamail with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws MessagingException { Properties javaMailConfiguration = new Properties(); javaMailConfiguration.put("mail.transport.protocol", "filetxt"); javaMailConfiguration.put("mail.files.path", "target/messages"); Session session = Session.getDefaultInstance(javaMailConfiguration); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); InternetAddress[] address = { new InternetAddress("[email protected]") }; message.setRecipients(Message.RecipientType.TO, address); Date now = new Date(); message.setSubject("JavaMail test at " + now); message.setSentDate(now); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("Body text version", "UTF-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<p>Body's text <strong>(html)</strong></p><p>Body html version</p>", "text/html; charset=UTF-8"); Multipart multiPart = new MimeMultipart("alternative"); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); session.getTransport().sendMessage(message, address); }
Example 4
Source File: ExampleSendNoRuleAdvTest.java From greenmail with Apache License 2.0 | 5 votes |
private void sendTestMails(String subject, String body) throws MessagingException { GreenMailUtil.sendTextEmailTest("to@localhost", "from@localhost", subject, body); // Create multipart MimeMultipart multipart = new MimeMultipart(); final MimeBodyPart part1 = new MimeBodyPart(); part1.setContent("body1", "text/plain"); multipart.addBodyPart(part1); final MimeBodyPart part2 = new MimeBodyPart(); part2.setContent("body2", "text/plain"); multipart.addBodyPart(part2); GreenMailUtil.sendMessageBody("to@localhost", "from@localhost", subject + "__2", multipart, null, ServerSetupTest.SMTP); }
Example 5
Source File: EmailModule.java From wandora with GNU General Public License v3.0 | 5 votes |
public boolean send(List<String> recipients,String from,String subject,Object message,String mimeType){ String charset; if(mimeType!=null){ Matcher m=charsetPattern.matcher(mimeType); if(m.find()){ charset=m.group(1).toUpperCase(); } else { charset=defaultCharset; mimeType+="; charset="+defaultCharset.toLowerCase(); } } else { charset=defaultCharset; mimeType=defaultContentType+"; charset="+defaultCharset.toLowerCase(); } try{ MimeBodyPart mimeBody=new MimeBodyPart(); mimeBody.setContent(message, mimeType); ArrayList<BodyPart> parts=new ArrayList<BodyPart>(); parts.add(mimeBody); return send(recipients, from, subject, parts); // byte[] content=message.getBytes(charset); // return send(recipients, from, subject, content, mimeType); } catch(MessagingException me){ logging.warn("Couldn't send email",me); return false; } /* catch(UnsupportedEncodingException uee){ logging.warn("Couldn't send email, unsupported encoding "+charset,uee); return false; }*/ }
Example 6
Source File: AutoSendEmail.java From AndroidTranslucentUI with Apache License 2.0 | 5 votes |
/** * �����ʼ� */ private void setMessage(String from,String title,String content) throws AddressException, MessagingException{ this.message.setFrom(new InternetAddress(from)); this.message.setSubject(title); MimeBodyPart textBody = new MimeBodyPart(); textBody.setContent(content,"text/html;charset=gbk"); this.multipart.addBodyPart(textBody); }
Example 7
Source File: MessageAlteringUtils.java From james-project with Apache License 2.0 | 5 votes |
private MimeBodyPart getErrorPart(Mail originalMail) throws MessagingException { MimeBodyPart errorPart = new MimeBodyPart(); errorPart.setContent(originalMail.getErrorMessage(), "text/plain"); errorPart.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); errorPart.setFileName("Reasons"); errorPart.setDisposition(javax.mail.Part.ATTACHMENT); return errorPart; }
Example 8
Source File: MimeMessageHelper.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Determine the MimeMultipart objects to use, which will be used * to store attachments on the one hand and text(s) and inline elements * on the other hand. * <p>Texts and inline elements can either be stored in the root element * itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED) or in a nested element * rather than the root element directly (MULTIPART_MODE_MIXED_RELATED). * <p>By default, the root MimeMultipart element will be of type "mixed" * (MULTIPART_MODE_MIXED) or "related" (MULTIPART_MODE_RELATED). * The main multipart element will either be added as nested element of * type "related" (MULTIPART_MODE_MIXED_RELATED) or be identical to the root * element itself (MULTIPART_MODE_MIXED, MULTIPART_MODE_RELATED). * @param mimeMessage the MimeMessage object to add the root MimeMultipart * object to * @param multipartMode the multipart mode, as passed into the constructor * (MIXED, RELATED, MIXED_RELATED, or NO) * @throws MessagingException if multipart creation failed * @see #setMimeMultiparts * @see #MULTIPART_MODE_NO * @see #MULTIPART_MODE_MIXED * @see #MULTIPART_MODE_RELATED * @see #MULTIPART_MODE_MIXED_RELATED */ protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode) throws MessagingException { switch (multipartMode) { case MULTIPART_MODE_NO: setMimeMultiparts(null, null); break; case MULTIPART_MODE_MIXED: MimeMultipart mixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED); mimeMessage.setContent(mixedMultipart); setMimeMultiparts(mixedMultipart, mixedMultipart); break; case MULTIPART_MODE_RELATED: MimeMultipart relatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED); mimeMessage.setContent(relatedMultipart); setMimeMultiparts(relatedMultipart, relatedMultipart); break; case MULTIPART_MODE_MIXED_RELATED: MimeMultipart rootMixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED); mimeMessage.setContent(rootMixedMultipart); MimeMultipart nestedRelatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED); MimeBodyPart relatedBodyPart = new MimeBodyPart(); relatedBodyPart.setContent(nestedRelatedMultipart); rootMixedMultipart.addBodyPart(relatedBodyPart); setMimeMultiparts(rootMixedMultipart, nestedRelatedMultipart); break; default: throw new IllegalArgumentException("Only multipart modes MIXED_RELATED, RELATED and NO supported"); } }
Example 9
Source File: Sign.java From james-project with Apache License 2.0 | 4 votes |
/** * A text file with the massaged contents of {@link #getExplanationText} * is attached to the original message. */ @Override protected MimeBodyPart getWrapperBodyPart(Mail mail) throws MessagingException, IOException { String explanationText = getExplanationText(); // if there is no explanation text there should be no wrapping if (explanationText == null) { return null; } MimeMessage originalMessage = mail.getMessage(); MimeBodyPart messagePart = new MimeBodyPart(); MimeBodyPart signatureReason = new MimeBodyPart(); String contentType = originalMessage.getContentType(); Object content = originalMessage.getContent(); if (contentType != null && content != null) { messagePart.setContent(content, contentType); } else { throw new MessagingException("Either the content type or the content is null"); } String headers = getMessageHeaders(originalMessage); signatureReason.setText(getReplacedExplanationText(getExplanationText(), getSignerName(), getKeyHolder().getSignerAddress(), mail.getMaybeSender().asString(), headers)); signatureReason.setFileName("SignatureExplanation.txt"); MimeMultipart wrapperMultiPart = new MimeMultipart(); wrapperMultiPart.addBodyPart(messagePart); wrapperMultiPart.addBodyPart(signatureReason); MimeBodyPart wrapperBodyPart = new MimeBodyPart(); wrapperBodyPart.setContent(wrapperMultiPart); return wrapperBodyPart; }
Example 10
Source File: SMTPAppender.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
/** Send the contents of the cyclic buffer as an e-mail message. */ protected void sendBuffer() { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. try { MimeBodyPart part = new MimeBodyPart(); StringBuffer sbuf = new StringBuffer(); String t = layout.getHeader(); if(t != null) sbuf.append(t); int len = cb.length(); for(int i = 0; i < len; i++) { //sbuf.append(MimeUtility.encodeText(layout.format(cb.get()))); LoggingEvent event = cb.get(); sbuf.append(layout.format(event)); if(layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { for(int j = 0; j < s.length; j++) { sbuf.append(s[j]); sbuf.append(Layout.LINE_SEP); } } } } t = layout.getFooter(); if(t != null) sbuf.append(t); part.setContent(sbuf.toString(), layout.getContentType()); Multipart mp = new MimeMultipart(); mp.addBodyPart(part); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); } catch(Exception e) { LogLog.error("Error occured while sending e-mail notification.", e); } }
Example 11
Source File: SMIMESign.java From james-project with Apache License 2.0 | 4 votes |
/** * A text file with the massaged contents of {@link #getExplanationText} * is attached to the original message. */ @Override protected MimeBodyPart getWrapperBodyPart(Mail mail) throws MessagingException, IOException { String explanationText = getExplanationText(); // if there is no explanation text there should be no wrapping if (explanationText == null) { return null; } MimeMessage originalMessage = mail.getMessage(); MimeBodyPart messagePart = new MimeBodyPart(); MimeBodyPart signatureReason = new MimeBodyPart(); String contentType = originalMessage.getContentType(); Object content = originalMessage.getContent(); if (contentType != null && content != null) { messagePart.setContent(content, contentType); } else { throw new MessagingException("Either the content type or the content is null"); } String headers = getMessageHeaders(originalMessage); signatureReason.setText(getReplacedExplanationText(getExplanationText(), getSignerName(), getKeyHolder().getSignerAddress(), mail.getMaybeSender().asString(), headers)); signatureReason.setFileName("SignatureExplanation.txt"); MimeMultipart wrapperMultiPart = new MimeMultipart(); wrapperMultiPart.addBodyPart(messagePart); wrapperMultiPart.addBodyPart(signatureReason); MimeBodyPart wrapperBodyPart = new MimeBodyPart(); wrapperBodyPart.setContent(wrapperMultiPart); return wrapperBodyPart; }
Example 12
Source File: SesSendNotificationHandler.java From smart-security-camera with GNU General Public License v3.0 | 4 votes |
public Parameters handleRequest(Parameters parameters, Context context) { context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); try { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setSubject(EMAIL_SUBJECT, "UTF-8"); message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM"))); message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) }); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT"))); MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = new MimeMultipart("alternative"); MimeBodyPart html = new MimeBodyPart(); cover.addBodyPart(html); wrap.setContent(cover); MimeMultipart content = new MimeMultipart("related"); message.setContent(content); content.addBodyPart(wrap); URL attachmentURL = new URL( System.getenv("S3_URL_PREFIX") + parameters.getS3Bucket() + '/' + parameters.getS3Key()); StringBuilder sb = new StringBuilder(); String id = UUID.randomUUID().toString(); sb.append("<img src=\"cid:"); sb.append(id); sb.append("\" alt=\"ATTACHMENT\"/>\n"); MimeBodyPart attachment = new MimeBodyPart(); DataSource fds = new URLDataSource(attachmentURL); attachment.setDataHandler(new DataHandler(fds)); attachment.setContentID("<" + id + ">"); attachment.setDisposition("attachment"); attachment.setFileName(fds.getName()); content.addBodyPart(attachment); String prettyPrintLabels = parameters.getRekognitionLabels().toString(); prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", ""); prettyPrintLabels = prettyPrintLabels.replace(",", "<br>"); html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "") + "</h2><p><i>Step Function ID : " + parameters.getStepFunctionID() + "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb + "</body></html>", "text/html"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient(); client.sendRawEmail(rawEmailRequest); // Convert Checked Exceptions to RuntimeExceptions to ensure that // they get picked up by the Step Function infrastructure } catch (MessagingException | IOException e) { throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e); } context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); return parameters; }
Example 13
Source File: MailDaemon.java From Open-Lowcode with Eclipse Public License 2.0 | 4 votes |
/** * sends invitation * * @param session session connection to the SMTP server * @param toemails list of recipient e-mails * @param subject invitation subject * @param body invitation start * @param fromemail user sending the invitation * @param startdate start date of the invitation * @param enddate end date of the invitation * @param location location of the invitation * @param uid unique id * @param cancelation true if this is a cancelation */ private void sendInvitation(Session session, String[] toemails, String subject, String body, String fromemail, Date startdate, Date enddate, String location, String uid, boolean cancelation) { try { // prepare mail mime message MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap(); mimetypes.addMimeTypes("text/calendar ics ICS"); // register the handling of text/calendar mime type MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap(); mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain"); MimeMessage msg = new MimeMessage(session); // set message headers msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); InternetAddress fromemailaddress = new InternetAddress(fromemail); msg.setFrom(fromemailaddress); msg.setReplyTo(InternetAddress.parse(fromemail, false)); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); // set recipient InternetAddress[] recipients = new InternetAddress[toemails.length + 1]; String attendeesinvcalendar = ""; for (int i = 0; i < toemails.length; i++) { recipients[i] = new InternetAddress(toemails[i]); attendeesinvcalendar += "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:" + toemails[i] + "\n"; } recipients[toemails.length] = fromemailaddress; msg.setRecipients(Message.RecipientType.TO, recipients); Multipart multipart = new MimeMultipart("alternative"); // set body MimeBodyPart descriptionPart = new MimeBodyPart(); descriptionPart.setContent(body, "text/html; charset=utf-8"); multipart.addBodyPart(descriptionPart); // set invitation BodyPart calendarPart = new MimeBodyPart(); String method = "METHOD:REQUEST\n"; if (cancelation) method = "METHOD:CANCEL\n"; String calendarContent = "BEGIN:VCALENDAR\n" + method + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n" + "BEGIN:VEVENT\n" + "DTSTAMP:" + iCalendarDateFormat.format(new Date()) + "\n" + "DTSTART:" + iCalendarDateFormat.format(startdate) + "\n" + "DTEND:" + iCalendarDateFormat.format(enddate) + "\n" + "SUMMARY:" + subject + "\n" + "UID:" + uid + "\n" + attendeesinvcalendar + "ORGANIZER:MAILTO:" + fromemail + "\n" + "LOCATION:" + location + "\n" + "DESCRIPTION:" + subject + "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR"; calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage"); calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL"); multipart.addBodyPart(calendarPart); msg.setContent(multipart); logger.severe("Invitation is ready"); Transport.send(msg); logger.severe("EMail Invitation Sent Successfully!! to " + attendeesinvcalendar); } catch (Exception e) { logger.severe( "--- Exception in sending invitation --- " + e.getClass().toString() + " - " + e.getMessage()); if (e.getCause() != null) logger.severe(" cause " + e.getCause().getClass().toString() + " - " + e.getCause().getMessage()); throw new RuntimeException("email sending error " + e.getMessage() + " for server = server:" + this.smtpserver + " - port:" + this.port + " - user:" + this.user); } }
Example 14
Source File: ExampleSendReceiveMessageWithInlineAttachmentTest.java From greenmail with Apache License 2.0 | 4 votes |
private void sendMailMessageWithInlineAttachment() throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(false), emailAddress, "Message with inline attachment"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent("This is some text to be displayed inline", "text/plain"); // Try not to display text as separate attachment textPart.setDisposition(Part.INLINE); Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); message.setContent(mp); Transport.send(message); }
Example 15
Source File: EmailService.java From mysql-backup4j with MIT License | 4 votes |
/** * This function will send an email * and add the generated sql file as an attachment * @return boolean */ boolean sendMail() { if(!this.isPropertiesSet()) { logger.debug(LOG_PREFIX + ": Required Mail Properties are not set. Attachments will not be sent"); return false; } Properties prop = new Properties(); prop.put("mail.smtp.auth", true); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.host", this.host); prop.put("mail.smtp.port", this.port); prop.put("mail.smtp.ssl.trust", host); logger.debug(LOG_PREFIX + ": Mail properties set"); Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); logger.debug(LOG_PREFIX + ": Mail Session Created"); try { // create a default mime message object Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAdd)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAdd)); message.setSubject(subject); // body part for message MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(msg, "text/html"); // body part for attachments MimeBodyPart attachmentBodyPart = new MimeBodyPart(); logger.debug(LOG_PREFIX + ": " + this.attachments.length + " attachments found"); for (File file: this.attachments) { attachmentBodyPart.attachFile(file); } // create a multipart to combine them together Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); multipart.addBodyPart(attachmentBodyPart); //now set the multipart as the content of the message message.setContent(multipart); // send the message Transport.send(message); logger.debug(LOG_PREFIX + ": MESSAGE SENT SUCCESSFULLY"); return true; } catch (Exception e) { logger.debug(LOG_PREFIX + ": MESSAGE NOT SENT. " + e.getLocalizedMessage()); e.printStackTrace(); return false; } }
Example 16
Source File: MailOutput.java From NNAnalytics with Apache License 2.0 | 4 votes |
/** * Write and send an email. * * @param subject email subject * @param html the exact html to send out via email * @param mailHost email host * @param emailTo email to address * @param emailCc email cc addresses * @param emailFrom email from address * @throws Exception if email fails to send */ public static void write( String subject, String html, String mailHost, String[] emailTo, String[] emailCc, String emailFrom) throws Exception { InternetAddress[] to = new InternetAddress[emailTo.length]; for (int i = 0; i < emailTo.length && i < to.length; i++) { to[i] = new InternetAddress(emailTo[i]); } InternetAddress[] cc = null; if (emailCc != null) { cc = new InternetAddress[emailCc.length]; for (int i = 0; i < emailCc.length && i < cc.length; i++) { cc[i] = new InternetAddress(emailCc[i]); } } // Sender's email ID needs to be mentioned InternetAddress from = new InternetAddress(emailFrom); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(MAIL_SMTP_HOST, mailHost); // Get the Session object. Session session = Session.getInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // INodeSet From: header field of the header. message.setFrom(from); // INodeSet To: header field of the header. message.addRecipients(Message.RecipientType.TO, to); if (cc != null && cc.length != 0) { message.addRecipients(Message.RecipientType.CC, cc); } // INodeSet Subject: header field message.setSubject(subject); // Send the actual HTML message, as big as you like MimeBodyPart bodyHtml = new MimeBodyPart(); bodyHtml.setContent(html, MAIL_CONTENT_TEXT_HTML); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyHtml); message.setContent(multipart); // Send message Transport.send(message); }
Example 17
Source File: MailUtil.java From mail-micro-service with Apache License 2.0 | 4 votes |
/** * 发送邮件(负载均衡) * * @param key 负载均衡key * @param to 收件人,多个收件人用 {@code ;} 分隔 * @param cc 抄送人,多个抄送人用 {@code ;} 分隔 * @param bcc 密送人,多个密送人用 {@code ;} 分隔 * @param subject 主题 * @param content 内容,可引用内嵌图片,引用方式:{@code <img src="cid:内嵌图片文件名" />} * @param images 内嵌图片 * @param attachments 附件 * @return 如果邮件发送成功,则返回 {@code true},否则返回 {@code false} */ public boolean sendByLoadBalance(String key, String to, String cc, String bcc, String subject, String content, File[] images, File[] attachments){ log.info("loadBalanceKey={}", key); Properties properties = MailManager.getProperties(key); log.info("properties={}", properties); Session session = MailManager.getSession(key); MimeMessage message = new MimeMessage(session); String username = properties.getProperty("mail.username"); ThreadLocalUtils.put(Constants.CURRENT_MAIL_FROM, username); try { message.setFrom(new InternetAddress(username)); addRecipients(message, Message.RecipientType.TO, to); if (cc != null) { addRecipients(message, Message.RecipientType.CC, cc); } if (bcc != null) { addRecipients(message, Message.RecipientType.BCC, bcc); } message.setSubject(subject, CHART_SET_UTF8); // 最外层部分 MimeMultipart wrapPart = new MimeMultipart("mixed"); MimeMultipart htmlWithImageMultipart = new MimeMultipart("related"); // 文本部分 MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(content, CONTENT_TYPE_HTML); htmlWithImageMultipart.addBodyPart(htmlPart); // 内嵌图片部分 addImages(images, htmlWithImageMultipart); MimeBodyPart htmlWithImageBodyPart = new MimeBodyPart(); htmlWithImageBodyPart.setContent(htmlWithImageMultipart); wrapPart.addBodyPart(htmlWithImageBodyPart); // 附件部分 addAttachments(attachments, wrapPart); message.setContent(wrapPart); Transport.send(message); return true; } catch (Exception e) { log.error("sendByLoadBalance error!", e.getMessage(), "loadBalanceKey={}, properties={}, to={}, cc={}, " + "bcc={}, subject={}, content={}, images={}, attachments={}", key, properties, to, cc, bcc, subject, content, images, attachments, e); } return false; }
Example 18
Source File: BigAttachmentTest.java From subethasmtp with Apache License 2.0 | 4 votes |
/** */ public void testAttachments() throws Exception { if (BIGFILE_PATH.equals(TO_CHANGE)) { log.error("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !"); } assertNotSame("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !", TO_CHANGE, BIGFILE_PATH); Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "localhost"); props.setProperty("mail.smtp.port", SMTP_PORT+""); Session session = Session.getInstance(props); MimeMessage baseMsg = new MimeMessage(session); MimeBodyPart bp1 = new MimeBodyPart(); bp1.setHeader("Content-Type", "text/plain"); bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\""); // Attach the file MimeBodyPart bp2 = new MimeBodyPart(); FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH); DataHandler dh = new DataHandler(fileAttachment); bp2.setDataHandler(dh); bp2.setFileName(fileAttachment.getName()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bp1); multipart.addBodyPart(bp2); baseMsg.setFrom(new InternetAddress("Ted <[email protected]>")); baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress( "[email protected]")); baseMsg.setSubject("Test Big attached file message"); baseMsg.setContent(multipart); baseMsg.saveChanges(); log.debug("Send started"); Transport t = new SMTPTransport(session, new URLName("smtp://localhost:"+SMTP_PORT)); long started = System.currentTimeMillis(); t.connect(); t.sendMessage(baseMsg, new Address[] {new InternetAddress( "[email protected]")}); t.close(); started = System.currentTimeMillis() - started; log.info("Elapsed ms = "+started); WiserMessage msg = this.server.getMessages().get(0); assertEquals(1, this.server.getMessages().size()); assertEquals("[email protected]", msg.getEnvelopeReceiver()); File compareFile = File.createTempFile("attached", ".tmp"); log.debug("Writing received attachment ..."); FileOutputStream fos = new FileOutputStream(compareFile); ((MimeMultipart) msg.getMimeMessage().getContent()).getBodyPart(1).getDataHandler().writeTo(fos); fos.close(); log.debug("Checking integrity ..."); assertTrue(this.checkIntegrity(new File(BIGFILE_PATH), compareFile)); log.debug("Checking integrity DONE"); compareFile.delete(); }
Example 19
Source File: SMTPAppender.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
/** * Send the contents of the cyclic buffer as an e-mail message. */ private final void sendBuffer() { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. try { final MimeBodyPart part = new MimeBodyPart(); final StringBuilder sbuf = new StringBuilder(100); String t = layout.getHeader(); if (t != null) { sbuf.append(t); } final int len = cb.length(); for (int i = 0; i < len; i++) { //sbuf.append(MimeUtility.encodeText(layout.format(cb.get()))); final LoggingEvent event = cb.get(); sbuf.append(layout.format(event)); if (layout.ignoresThrowable()) { final String[] s = event.getThrowableStrRep(); if (s != null) { for (final String value : s) { sbuf.append(value); sbuf.append(Layout.LINE_SEP); } } } } t = layout.getFooter(); if (t != null) { sbuf.append(t); } part.setContent(sbuf.toString(), layout.getContentType()); final Multipart mp = new MimeMultipart(); mp.addBodyPart(part); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); } catch (final Exception e) { LogLog.error("Error occurred while sending e-mail notification.", e); } }
Example 20
Source File: SendEmail.java From AndroidAnimationExercise with Apache License 2.0 | 3 votes |
/** * 设置邮件 * * @param from 来源 * @param title 标题 * @param content 内容 * @throws AddressException * @throws MessagingException */ public void setMessage(String from, String title, String content) throws AddressException, MessagingException { this.message.setFrom(new InternetAddress(from)); this.message.setSubject(title); //纯文本的话用setText()就行,不过有附件就显示不出来内容了 MimeBodyPart textBody = new MimeBodyPart(); textBody.setContent(content, "text/html;charset=gbk"); this.multipart.addBodyPart(textBody); }