javax.mail.internet.MimeMessage#setContent ( )源码实例Demo

下面列出了javax.mail.internet.MimeMessage#setContent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: entando-components   文件: MailManager.java
private boolean send(String text, String subject, String[] recipientsTo, String[] recipientsCc, String[] recipientsBcc, String senderCode, Properties attachmentFiles, String contentType) throws ApsSystemException {
	Transport bus = null;
	try {
		Session session = this.prepareSession(this.getConfig());
		bus = this.prepareTransport(session, this.getConfig());
		MimeMessage msg = this.prepareVoidMimeMessage(session, subject, recipientsTo, recipientsCc, recipientsBcc, senderCode);
		if (attachmentFiles == null || attachmentFiles.isEmpty()) {
			msg.setContent(text, contentType + "; charset=utf-8");
		} else {
			Multipart multiPart = new MimeMultipart();
			this.addBodyPart(text, contentType, multiPart);
			this.addAttachments(attachmentFiles, multiPart);
			msg.setContent(multiPart);
		}
		msg.saveChanges();
		bus.send(msg);
	} catch (Throwable t) {
		throw new ApsSystemException("Error sending mail", t);
	} finally {
		closeTransport(bus);
	}
	return true;
}
 
@Test
public void isMdnSentAutomaticallyShouldManageItsMimeType() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                            "Disposition: MDN-sent-automatically",
                            "text/plain")
                    ));
    scriptPart.setHeader("Content-Type", "text/plain");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
源代码3 项目: syndesis   文件: EMailTestServer.java
public void deliverMultipartMessage(String user, String password, String from, String subject,
                                                                   String contentType, Object body) throws Exception {
    GreenMailUser greenUser = greenMail.setUser(user, password);
    MimeMultipart multiPart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setContent(body, contentType);

    Session session = GreenMailUtil.getSession(server.getServerSetup());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
    mimeMessage.setFrom(from);
    mimeMessage.setSubject(subject);
    mimeMessage.setContent(multiPart, "multipart/mixed");
    greenUser.deliver(mimeMessage);
}
 
源代码4 项目: javamail   文件: JMS2JavaMailTest.java
private static BytesMessage bytesMessageFor(MimeMessage mimeMessage, Address[] addresses) throws JMSException, IOException, MessagingException {
    mimeMessage.setContent("text", "plain/text");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeUTF("testProto");
    oos.writeObject(addresses == null ? new Address[0] : addresses);
    mimeMessage.writeTo(oos);
    BytesMessage message = Mockito.mock(BytesMessage.class);
    final ByteArrayInputStream messageBytes = new ByteArrayInputStream(out.toByteArray());
    when(message.readBytes(any(byte[].class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
        return messageBytes.read((byte[]) invocation.getArguments()[0]);
        }
    });
    return message;
}
 
源代码5 项目: contribution   文件: MailingListPublisher.java
/**
 * Publish post.
 *
 * @throws MessagingException if an error occurs while publishing.
 * @throws IOException if there are problems with reading file with the post text.
 */
public void publish() throws MessagingException, IOException {
    final Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", SMTP_HOST);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.auth", true);

    final Session session = Session.getInstance(props, null);
    final MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setSubject(String.format(SUBJECT_TEMPLATE, releaseNumber));
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.addRecipients(Message.RecipientType.TO,
            InternetAddress.parse(RECIPIENT_ADDRESS));

    final String post = new String(Files.readAllBytes(Paths.get(postFilename)),
            StandardCharsets.UTF_8);

    final BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(post, "text/plain");

    final Multipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);

    final Transport transport = session.getTransport("smtp");
    transport.connect(SMTP_HOST, username, password);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
 
@VisibleForTesting
void processTextBodyAsAttachment(MimeMessage mimeMessage) throws MessagingException {
    List<Header> contentHeaders = getContentHeadersFromMimeMessage(mimeMessage);

    removeAllContentHeaderFromMimeMessage(mimeMessage, contentHeaders);

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(createMimeBodyPartWithContentHeadersFromMimeMessage(mimeMessage, contentHeaders));

    mimeMessage.setContent(multipart);
    mimeMessage.saveChanges();
}
 
源代码7 项目: AsuraFramework   文件: SendMailJob.java
protected void setMimeMessageContent(MimeMessage mimeMessage, MailInfo mailInfo) 
    throws MessagingException {
    if (mailInfo.getContentType() == null) {
        mimeMessage.setText(mailInfo.getMessage());
    } else {
        mimeMessage.setContent(mailInfo.getMessage(), mailInfo.getContentType());
    }
}
 
源代码8 项目: james-project   文件: MimeMessageTest.java
protected MimeMessage getMultipartMessage() throws Exception {
    MimeMessage mmCreated = MimeMessageUtil.defaultMimeMessage();
    mmCreated.setSubject("test");
    mmCreated.addHeader("Date", "Tue, 16 Jan 2018 09:56:01 +0700 (ICT)");
    MimeMultipart mm = new MimeMultipart("alternative");
    mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test1\r\nContent-Type: text/plain; charset=Cp1252\r\n"
            .getBytes())), "first part òàù".getBytes()));
    mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test2\r\nContent-Type: text/plain; charset=Cp1252\r\nContent-Transfer-Encoding: quoted-printable\r\n"
            .getBytes())), "second part =E8=E8".getBytes()));
    mmCreated.setContent(mm);
    mmCreated.saveChanges();
    return mmCreated;
}
 
源代码9 项目: jeecg   文件: MailUtil.java
/**
 * 发送电子邮件
 * 
 * @param smtpHost
 *            发信主机
 * @param receiver
 *            邮件接收者
 * @param title
 *            邮件的标题
 * @param content
 *            邮件的内容
 * @param sender
 *            邮件发送者
 * @param user
 *            发送者邮箱用户名
 * @param pwd
 *            发送者邮箱密码
 * @throws MessagingException 
 */
public static void sendEmail(String smtpHost, String receiver,
		String title, String content, String sender, String user, String pwd) throws MessagingException
		 {
	Properties props = new Properties();
	props.put("mail.host", smtpHost);
	props.put("mail.transport.protocol", "smtp");
	// props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动!
	props.put("mail.smtp.auth", "true");
	Session s = Session.getDefaultInstance(props);
	s.setDebug(true);
	MimeMessage message = new MimeMessage(s);
	// 给消息对象设置发件人/收件人/主题/发信时间
	// 发件人的邮箱
	InternetAddress from = new InternetAddress(sender);
	message.setFrom(from);
	InternetAddress to = new InternetAddress(receiver);
	message.setRecipient(Message.RecipientType.TO, to);
	message.setSubject(title);
	message.setSentDate(new Date());
	// 给消息对象设置内容
	BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
	mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
	Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
	// 象(事实上可以存放多个)
	mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	message.setContent(mm);// 把mm作为消息对象的内容

	message.saveChanges();
	Transport transport = s.getTransport("smtp");
	transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的
	transport.sendMessage(message, message.getAllRecipients());
	transport.close();
}
 
源代码10 项目: lemon   文件: JavamailService.java
public void send(String to, String cc, String bcc, String subject,
        String content, JavamailConfig javamailConfig)
        throws MessagingException {
    logger.debug("send : {}, {}", to, subject);

    try {
        Properties props = createSmtpProperties(javamailConfig);
        String username = javamailConfig.getUsername();
        String password = javamailConfig.getPassword();

        // 创建Session实例对象
        Session session = Session.getInstance(props, new SmtpAuthenticator(
                username, password));
        session.setDebug(false);

        // 创建MimeMessage实例对象
        MimeMessage message = new MimeMessage(session);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置发送人
        message.setFrom(new InternetAddress(username));
        // 设置发送时间
        message.setSentDate(new Date());
        // 设置收件人
        message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
        // 设置html内容为邮件正文,指定MIME类型为text/html类型,并指定字符编码为gbk
        message.setContent(content, "text/html;charset=gbk");

        // 保存并生成最终的邮件内容
        message.saveChanges();

        // 发送邮件
        Transport.send(message);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}
 
源代码11 项目: FreeServer   文件: MailUtil.java
/**
 * 发送邮件
 * @param title 邮件标题
 * @param body  邮件正文
 */
public static void sendMaid(String title, String body){
    PropertiesUtil pro = new PropertiesUtil();
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.ssl.enable", "true");
    props.setProperty("mail.smtp.connectiontimeout", "5000");
    try{
        //1、创建session
        Session session = Session.getInstance(props);
        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        //session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport("smtp");
        //3、使用邮箱的用户名和密码连上邮件服务器,
        ts.connect(pro.getProperty("SERVER_HOST"), Integer.parseInt(pro.getProperty("SERVER_PORT")), pro.getProperty("SEND_USER"), pro.getProperty("PASSWORD"));
        //4、创建邮件
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(pro.getProperty("SEND_USER")));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(pro.getProperty("RECEIVE_USER")));
        //邮件的标题
        message.setSubject(title);
        //邮件的文本内容
        message.setContent(body, "text/html;charset=UTF-8");
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    } catch (Exception e){
        e.printStackTrace();
    }
}
 
源代码12 项目: java-technology-stack   文件: MimeMessageHelper.java
/**
 * 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");
	}
}
 
源代码13 项目: james-project   文件: MimeMessageBodyGenerator.java
public MimeMessage from(MimeMessage messageHoldingHeaders, Optional<String> plainText, Optional<String> htmlText) throws MessagingException {
    Preconditions.checkNotNull(messageHoldingHeaders);
    Preconditions.checkNotNull(plainText);
    Preconditions.checkNotNull(htmlText);
    if (htmlText.isPresent()) {
        messageHoldingHeaders.setContent(generateMultipart(htmlText.get(), plainText));
    } else {
        messageHoldingHeaders.setText(plainText.orElse(EMPTY_TEXT));
    }
    return messageHoldingHeaders;
}
 
源代码14 项目: studio   文件: EmailMessageSender.java
protected boolean sendEmail(final String subject, final String content, final String userEmailAddress,
                            final String replyTo, final String personalFromName) {
    boolean success = true;
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(userEmailAddress));
            InternetAddress[] replyTos = new InternetAddress[1];
            if ((replyTo != null) && (!"".equals(replyTo))) {
                replyTos[0] = new InternetAddress(replyTo);
                mimeMessage.setReplyTo(replyTos);
            }
            InternetAddress fromAddress = new InternetAddress(getDefaultFromAddress());
            if (personalFromName != null)
                fromAddress.setPersonal(personalFromName);
            mimeMessage.setFrom(fromAddress);
            mimeMessage.setContent(content, "text/html; charset=utf-8");
            mimeMessage.setSubject(subject);
            logger.debug("sending email to [" + userEmailAddress + "]subject subject :[" + subject + "]");
        }
    };
    try {
        if (isAuthenticatedSMTP()) {
            emailService.send(preparator);
        } else {
            emailServiceNoAuth.send(preparator);
        }
    } catch (MailException ex) {
        // simply log it and go on...
        logger.error("Error sending email notification to:" + userEmailAddress, ex);

        success = false;
    }

    return success;
}
 
public static void main(String[] args) throws Exception {

        // Create a Properties object to contain connection configuration information.
    	Properties props = System.getProperties();
    	props.put("mail.transport.protocol", "smtp");
    	props.put("mail.smtp.port", port);
    	props.put("mail.smtp.starttls.enable", "true");
    	props.put("mail.smtp.auth", "true");

        // Create a Session object to represent a mail session with the specified properties.
    	Session session = Session.getDefaultInstance(props);

        // Create a message with the specified information.
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senderAddress,senderName));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses));
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses));

        msg.setSubject(subject);
        msg.setContent(htmlBody,"text/html");

        // Add headers for configuration set and message tags to the message.
        msg.setHeader("X-SES-CONFIGURATION-SET", configurationSet);
        msg.setHeader("X-SES-MESSAGE-TAGS", tag0);
        msg.setHeader("X-SES-MESSAGE-TAGS", tag1);

        // Create a transport.
        Transport transport = session.getTransport();

        // Send the message.
        try {
            System.out.println("Sending...");

            // Connect to Amazon Pinpoint using the SMTP username and password you specified above.
            transport.connect(smtpEndpoint, smtpUsername, smtpPassword);

            // Send the email.
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        }
        catch (Exception ex) {
            System.out.println("The email wasn't sent. Error message: "
                + ex.getMessage());
        }
        finally {
            // Close the connection to the SMTP server.
            transport.close();
        }
    }
 
源代码16 项目: karaf-decanter   文件: EmailAlerter.java
@Override
public void handleEvent(Event event) {
    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        // set from
        if (event.getProperty("from") != null) {
            message.setFrom(new InternetAddress(event.getProperty("from").toString()));
        } else if (event.getProperty("alert.email.from") != null) {
            message.setFrom(new InternetAddress(event.getProperty("alert.email.from").toString()));
        } else if (from != null){
            message.setFrom(from);
        } else {
            message.setFrom("[email protected]");
        }
        // set to
        if (event.getProperty("to") != null) {
            message.addRecipients(Message.RecipientType.TO, event.getProperty("to").toString());
        } else if (event.getProperty("alert.email.to") != null) {
            message.addRecipients(Message.RecipientType.TO, event.getProperty("alert.email.to").toString());
        } else if (to != null) {
            message.addRecipients(Message.RecipientType.TO, to);
        } else {
            LOGGER.warn("to destination is not defined");
            return;
        }
        // set cc
        if (event.getProperty("cc") != null) {
            message.addRecipients(Message.RecipientType.CC, event.getProperty("cc").toString());
        } else if (event.getProperty("alert.email.cc") != null) {
            message.addRecipients(Message.RecipientType.CC, event.getProperty("alert.email.cc").toString());
        } else if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        // set bcc
        if (event.getProperty("bcc") != null) {
            message.addRecipients(Message.RecipientType.BCC, event.getProperty("bcc").toString());
        } else if (event.getProperty("alert.email.bcc") != null) {
            message.addRecipients(Message.RecipientType.BCC, event.getProperty("alert.email.bcc").toString());
        } else if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }
        // set subject
        message.setSubject(formatter.formatSubject(subjectTemplate, event));
        // set body
        String contentType = bodyType;
        contentType = (event.getProperty("body.type") != null) ? event.getProperty("body.type").toString() : contentType;
        contentType = (event.getProperty("alert.email.body.type") != null) ? event.getProperty("alert.email.body.type").toString() : contentType;
        message.setContent(formatter.formatBody(bodyTemplate, event), contentType);
        // send email
        if (properties.get("mail.smtp.user") != null) {
            Transport.send(message, (String) properties.get("mail.smtp.user"), (String) properties.get("mail.smtp.password"));
        } else {
            Transport.send(message);
        }
    } catch (Exception e) {
        LOGGER.error("Can't send the alert e-mail", e);
    }
}
 
源代码17 项目: james-project   文件: 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));
    }
    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(InternetAddress[]::new));
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses.toArray(InternetAddress[]::new));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(InternetAddress[]::new));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(InternetAddress[]::new));
    }

    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;
}
 
源代码18 项目: mail-micro-service   文件: MailUtil.java
/**
 * 发送邮件(负载均衡)
 *
 * @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;
}
 
源代码19 项目: Singularity   文件: SingularitySmtpSender.java
private void sendMail(
  List<String> toList,
  List<String> ccList,
  String subject,
  String body
) {
  final SMTPConfiguration smtpConfiguration = maybeSmtpConfiguration.get();

  boolean useAuth = false;

  if (
    smtpConfiguration.getUsername().isPresent() &&
    smtpConfiguration.getPassword().isPresent()
  ) {
    useAuth = true;
  } else if (
    smtpConfiguration.getUsername().isPresent() ||
    smtpConfiguration.getPassword().isPresent()
  ) {
    LOG.warn(
      "Not using smtp authentication because username ({}) or password ({}) was not present",
      smtpConfiguration.getUsername().isPresent(),
      smtpConfiguration.getPassword().isPresent()
    );
  }

  try {
    final Session session = createSession(smtpConfiguration, useAuth);

    MimeMessage message = new MimeMessage(session);

    Address[] toArray = getAddresses(toList);
    message.addRecipients(RecipientType.TO, toArray);

    if (!ccList.isEmpty()) {
      Address[] ccArray = getAddresses(ccList);
      message.addRecipients(RecipientType.CC, ccArray);
    }

    message.setFrom(new InternetAddress(smtpConfiguration.getFrom()));

    message.setSubject(MimeUtility.encodeText(subject, "utf-8", null));
    message.setContent(body, "text/html; charset=utf-8");

    LOG.trace(
      "Sending a message to {} - {}",
      Arrays.toString(toArray),
      getEmailLogFormat(toList, subject)
    );

    Transport.send(message);
  } catch (Throwable t) {
    LOG.warn("Unable to send message {}", getEmailLogFormat(toList, subject), t);
    exceptionNotifier.notify(
      String.format("Unable to send message (%s)", t.getMessage()),
      t,
      ImmutableMap.of("subject", subject)
    );
  }
}
 
源代码20 项目: sakai   文件: BasicEmailService.java
/**
 * Sets the content for a message. Also attaches files to the message.
 * @throws MessagingException
 */
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg,
		String contentType, String charset, String multipartSubtype) throws AttachmentSizeException, MessagingException {

	ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
	if (attachments != null && attachments.size() > 0) {
		int maxAttachmentSize = serverConfigurationService.getInt(MAIL_SENDFROMSAKAI_MAXSIZE, DEFAULT_MAXSIZE);
		long attachmentRunningTotal = 0L;

		// Add attachments to messages
		for (Attachment attachment : attachments) {
			// attach the file to the message
			MimeBodyPart mbp = createAttachmentPart(attachment);
			long mbpSize = (long) mbp.getSize();

			if (mbpSize == -1L) {
				// This is normal. See MimeBodyPart documentation.
				mbpSize = attachment.getSizeIfFile().orElse(-1L);
			}

			if (mbpSize == -1L) {
				log.warn("Failed to get size of email attachment. This could result in the limit being exceeded");
			}

			if ( (attachmentRunningTotal + mbpSize) < maxAttachmentSize ) {
				embeddedAttachments.add(mbp);
				attachmentRunningTotal = attachmentRunningTotal + mbpSize;
			} else {
				throw new AttachmentSizeException("Attachments too large", attachmentRunningTotal + mbpSize);
			}
		}
	}

	// if no direct attachments, keep the message simple and add the content as text.
	if (embeddedAttachments.size() == 0) {
		// if no contentType specified, go with text/plain
		if (contentType == null) {
			msg.setText(content, charset);
		} else {
			msg.setContent(content, contentType);
		}
	} else {
		// the multipart was constructed (ie. attachments available), use it as the message content
		// create a multipart container
		Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype) : new MimeMultipart();

		// create a body part for the message text
		MimeBodyPart msgBodyPart = new MimeBodyPart();
		if (contentType == null) {
			msgBodyPart.setText(content, charset);
		} else {
			msgBodyPart.setContent(content, contentType);
		}

		// add the message part to the container
		multipart.addBodyPart(msgBodyPart);

		// add attachments
		for (MimeBodyPart attachPart : embeddedAttachments) {
			multipart.addBodyPart(attachPart);
		}

		// set the multipart container as the content of the message
		msg.setContent(multipart);
	}
}