javax.mail.Session#getDefaultInstance ( )源码实例Demo

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

源代码1 项目: smart-admin   文件: SmartSendMailUtil.java
/**
 * 创建session
 *
 * @author lidoudou
 * @date 2019/2/16 14:59
 */
private static Session createSSLSession(String sendSMTPHost, String port, String userName, String pwd) {
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置
    Properties props = new Properties(); // 参数配置

    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", pwd);
    props.setProperty("mail.smtp.host", sendSMTPHost);
    props.setProperty("mail.smtp.port", port);
    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.auth", "true");

    // 2. 根据配置创建会话对象, 用于和邮件服务器交互
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        //身份认证
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, pwd);
        }
    });
    session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
    return session;
}
 
源代码2 项目: anyline   文件: Pop3Util.java
/** 
 *  
 * @param fr 发送人姓名 
 * @param to 收件人地址 
 * @param title 邮件主题 
 * @param content  邮件内容 
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][centent:{}]", fr, to, title, content); 
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT, fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title); 
		msg.setContent(content, "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST, config.ACCOUNT, config.PASSWORD); 
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
源代码3 项目: teammates   文件: JavamailService.java
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
源代码4 项目: sc2gears   文件: ServerUtils.java
/**
 * Sends an email.
 * @return true if no error occurred, false otherwise
 */
public static boolean sendEmail( final InternetAddress from, final InternetAddress to, final InternetAddress cc, final String subject, final String body ) {
	LOGGER.info( "Sending email to: " + to.toString() + ", subject: " + subject );
	final Session session = Session.getDefaultInstance( new Properties(), null );
	try {
		final Message message = new MimeMessage( session );
		message.setFrom( from );
		message.addRecipient( Message.RecipientType.TO, to );
		if ( cc != null )
			message.addRecipient( Message.RecipientType.CC, cc );
		message.addRecipient( Message.RecipientType.BCC, ADMIN_EMAIL );
		message.setSubject( "[Sc2gears Database] " + subject );
		message.setText( body );
		Transport.send( message );
		return true;
	} catch ( final Exception e ) {
		LOGGER.log( Level.SEVERE, "Failed to send email!", e );
		return false;
	}
}
 
源代码5 项目: commons-email   文件: MimeMessageParserTest.java
@Test
public void testParseInlineCID() throws Exception
{
    final Session session = Session.getDefaultInstance(new Properties());
    final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/html-attachment.eml"));
    final MimeMessageParser mimeMessageParser = new MimeMessageParser(message);

    mimeMessageParser.parse();

    assertEquals("Test", mimeMessageParser.getSubject());
    assertNotNull(mimeMessageParser.getMimeMessage());
    assertTrue(mimeMessageParser.isMultipart());
    assertTrue(mimeMessageParser.hasHtmlContent());
    assertNotNull(mimeMessageParser.getHtmlContent());
    assertTrue(mimeMessageParser.getTo().size() == 1);
    assertTrue(mimeMessageParser.getCc().size() == 0);
    assertTrue(mimeMessageParser.getBcc().size() == 0);
    assertEquals("[email protected]", mimeMessageParser.getFrom());
    assertEquals("[email protected]", mimeMessageParser.getReplyTo());
    assertTrue(mimeMessageParser.hasAttachments());

    assertTrue(mimeMessageParser.getContentIds().contains("[email protected]"));
    assertFalse(mimeMessageParser.getContentIds().contains("part2"));

    final DataSource ds = mimeMessageParser.findAttachmentByCid("[email protected]");
    assertNotNull(ds);
    assertEquals(ds, mimeMessageParser.getAttachmentList().get(0));
}
 
源代码6 项目: OrigamiSMTP   文件: TestSMTPServerTest.java
private void sendTestMessage() throws AddressException, MessagingException
{
           Properties props = System.getProperties();
           props.put("mail.smtp.host","localhost");
           props.put("mail.smtp.port","2525");
           props.put("mail.smtp.socketFactory.port","2525");
           //props.put("mail.smtp.starttls.enable","true");
           Session session = Session.getDefaultInstance(props);
           MimeMessage msg = new MimeMessage(session);
           msg.setFrom(new InternetAddress("[email protected]"));
           msg.setRecipient(javax.mail.Message.RecipientType.TO,new InternetAddress("[email protected]"));
           msg.setSubject("Test email");
           msg.setText("Hello!");
           Transport.send(msg);
}
 
源代码7 项目: KJFrameForAndroid   文件: SimpleMailSender.java
/**
 * 以文本格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件的信息
 */
public boolean sendTextMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(),
                mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session
            .getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
源代码8 项目: javamail   文件: SmtpJmsTransportTest.java
@Test
public void testSendInvalidPriority() throws Exception {
    SmtpJmsTransport transport = new SmtpJmsTransport(Session.getDefaultInstance(new Properties()), new URLName("jsm"));
    Message message = Mockito.mock(Message.class);
    when(message.getHeader(eq(SmtpJmsTransport.X_SEND_PRIORITY))).thenReturn(new String[]{"invalid"});
    when(message.getFrom()).thenReturn(new Address[] { new InternetAddress("[email protected]") });
    transport.sendMessage(message, new Address[] { new InternetAddress("[email protected]") });
    verify(bytesMessage, never()).setJMSPriority(anyInt());
}
 
源代码9 项目: journaldev   文件: SSLEmail.java
/**
   Outgoing Mail (SMTP) Server
   requires TLS or SSL: smtp.gmail.com (use authentication)
   Use Authentication: Yes
   Port for SSL: 465
 */
public static void main(String[] args) {
	final String fromEmail = "[email protected]";
	final String password = "my_pwd";
	final String toEmail = "[email protected]";
	
	System.out.println("SSLEmail Start");
	Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
	props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
	props.put("mail.smtp.socketFactory.class",
			"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
	props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
	props.put("mail.smtp.port", "465"); //SMTP Port
	
	Authenticator auth = new Authenticator() {
		//override the getPasswordAuthentication method
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(fromEmail, password);
		}
	};
	
	Session session = Session.getDefaultInstance(props, auth);
	System.out.println("Session created");
    EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");

    EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");

    EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");

}
 
源代码10 项目: aws-doc-sdk-examples   文件: SendMessage.java
public static void send(SesClient client,
                        String sender,
                        String recipient,
                        String subject,
                        String bodyText,
                        String bodyHTML
) throws AddressException, MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());

    // Create a new MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Add subject, from and to lines.
    message.setSubject(subject, "UTF-8");
    message.setFrom(new InternetAddress(sender));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

    // Create a multipart/alternative child container.
    MimeMultipart msgBody = new MimeMultipart("alternative");

    // Create a wrapper for the HTML and text parts.
    MimeBodyPart wrap = new MimeBodyPart();

    // Define the text part.
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(bodyText, "text/plain; charset=UTF-8");

    // Define the HTML part.
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");

    // Add the text and HTML parts to the child container.
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);

    // Add the child container to the wrapper object.
    wrap.setContent(msgBody);

    // Create a multipart/mixed parent container.
    MimeMultipart msg = new MimeMultipart("mixed");

    // Add the parent container to the message.
    message.setContent(msg);

    // Add the multipart/alternative part to the message.
    msg.addBodyPart(wrap);

    try {
        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);

        ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

        byte[] arr = new byte[buf.remaining()];
        buf.get(arr);

        SdkBytes data = SdkBytes.fromByteArray(arr);

        RawMessage rawMessage = RawMessage.builder()
                .data(data)
                .build();

        SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                .rawMessage(rawMessage)
                .build();

        client.sendRawEmail(rawEmailRequest);

    } catch (SesException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }


}
 
源代码11 项目: baleen   文件: MimeReader.java
@Override
protected void doGetNext(final JCas jCas) throws IOException, CollectionException {
  final Path path = files.pop();
  final File file = path.toFile();

  final int left = files.size();

  getMonitor()
      .info(
          "Processing {} ({} %)",
          file.getAbsolutePath(), String.format("%.2f", 100 * (total - left) / (double) total));

  try (FileInputStream is = new FileInputStream(file)) {
    final Session s = Session.getDefaultInstance(new Properties());
    final MimeMessageParser parser = new MimeMessageParser(new MimeMessage(s, is));
    parser.parse();
    final MimeMessage message = parser.getMimeMessage();

    final DocumentAnnotation da = UimaSupport.getDocumentAnnotation(jCas);
    da.setTimestamp(calculateBestDate(message, file));
    da.setDocType("email");
    da.setDocumentClassification("O");
    String source = file.getAbsolutePath().substring(rootFolder.length());
    da.setSourceUri(source);
    da.setLanguage("en");

    // Add all headers as metadata, with email prefix
    final Enumeration<Header> allHeaders = message.getAllHeaders();
    while (allHeaders.hasMoreElements()) {
      final Header header = allHeaders.nextElement();
      addMetadata(jCas, "email." + header.getName(), header.getValue());
    }

    addMetadata(jCas, "from", parser.getFrom());
    addMetadata(jCas, "to", parser.getTo());
    addMetadata(jCas, "cc", parser.getCc());
    addMetadata(jCas, "bcc", parser.getBcc());
    addMetadata(jCas, "subject", parser.getSubject());

    // Add fake title
    addMetadata(jCas, "title", parser.getSubject());

    String actualContent = parser.getPlainContent();

    if (actualContent == null) {
      actualContent = "";
    }

    // TODO: At this point we could create a representation of the addresses, etc in the content
    // eg a table of to, from, and etc
    // then annotate them a commsidentifier, date, person.
    // We could also create relations between sender and receiver

    String content = actualContent + "\n\n---\n\n";

    final String headerBlock = createHeaderBlock(content.length(), jCas, parser);
    content = content + headerBlock;

    final Text text = new Text(jCas);
    text.setBegin(0);
    text.setEnd(actualContent.length());
    text.addToIndexes();

    extractContent(new ByteArrayInputStream(content.getBytes()), source, jCas);
  } catch (final Exception e) {
    getMonitor().warn("Discarding message", e);
  }
}
 
源代码12 项目: cxf   文件: AttachmentSerializerTest.java
@Test
public void testMessageMTOM() throws Exception {
    MessageImpl msg = new MessageImpl();

    Collection<Attachment> atts = new ArrayList<>();
    AttachmentImpl a = new AttachmentImpl("test.xml");

    InputStream is = getClass().getResourceAsStream("my.wav");
    ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream");
    a.setDataHandler(new DataHandler(ds));

    atts.add(a);

    msg.setAttachments(atts);

    // Set the SOAP content type
    msg.put(Message.CONTENT_TYPE, "application/soap+xml");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.setContent(OutputStream.class, out);

    AttachmentSerializer serializer = new AttachmentSerializer(msg);

    serializer.writeProlog();

    String ct = (String) msg.get(Message.CONTENT_TYPE);
    assertTrue(ct.indexOf("multipart/related;") == 0);
    assertTrue(ct.indexOf("start=\"<[email protected]>\"") > -1);
    assertTrue(ct.indexOf("start-info=\"application/soap+xml\"") > -1);

    out.write("<soap:Body/>".getBytes());

    serializer.writeAttachments();

    out.flush();
    DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage inMsg = new MimeMessage(session);
    inMsg.setContent(mpart);

    inMsg.addHeaderLine("Content-Type: " + ct);

    MimeMultipart multipart = (MimeMultipart) inMsg.getContent();

    MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0);
    assertEquals("application/xop+xml; charset=UTF-8; type=\"application/soap+xml\"",
                 part.getHeader("Content-Type")[0]);
    assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<[email protected]>", part.getHeader("Content-ID")[0]);

    InputStream in = part.getDataHandler().getInputStream();
    ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
    IOUtils.copy(in, bodyOut);
    out.close();
    in.close();

    assertEquals("<soap:Body/>", bodyOut.toString());

    MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1);
    assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]);
    assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]);

}
 
源代码13 项目: james-project   文件: MimeMessageWrapper.java
private MimeMessageWrapper() {
    super(Session.getDefaultInstance(new Properties()));
}
 
源代码14 项目: Mario   文件: DefaultMailSender.java
public DefaultMailSender() {
	props = System.getProperties();
	session = Session.getDefaultInstance(props, null);
	mimeMessage = new MimeMessage(session);
	multipart = new MimeMultipart();
}
 
源代码15 项目: mobikul-standalone-pos   文件: Mail.java
public boolean send() throws Exception {
        Properties props = _setProperties();

        if (!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") &&
                !_subject.equals("") && !_body.equals("")) {

            Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(ApplicationConstants.USERNAME_FOR_SMTP, ApplicationConstants.PASSWORD_FOR_SMTP);
                }
            });
            SMTPAuthenticator authentication = new SMTPAuthenticator();
            javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(props, authentication));
            msg.setFrom(new InternetAddress(_from));

            InternetAddress[] addressTo = new InternetAddress[_to.length];
            for (int i = 0; i < _to.length; i++) {
                addressTo[i] = new InternetAddress(_to[i]);
            }
            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

            msg.setSubject(_subject);
            msg.setSentDate(new Date());

// setup message body
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(_body);
            _multipart.addBodyPart(messageBodyPart);

// Put parts in message
            msg.setContent(_multipart);

// send email
            String protocol = "smtp";
            props.put("mail." + protocol + ".auth", "true");
            Transport t = session.getTransport(protocol);
            try {
                t.connect(ApplicationConstants.HOST_FOR_MAIL, ApplicationConstants.USERNAME_FOR_SMTP, ApplicationConstants.PASSWORD_FOR_SMTP);
                t.sendMessage(msg, msg.getAllRecipients());
            } finally {
                t.close();
            }

            return true;
        } else {
            return false;
        }
    }
 
源代码16 项目: Login-System-SSM   文件: SignAdminAction.java
@Override
	protected ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response, Object object, BindException exception)
			throws Exception {
		Admin admin = (Admin) object;  //将数据封装起来
System.out.println("表单提交过来时的数据是:"+admin.toString());

			if (adminService.addAdmin(admin)) {    //调用该方法,将数据持久到数据库中,如果持久化成功,则发送邮件给当前的注册用户
				try {
					String host = "smtp.qq.com"; // 邮件服务器
					String from = "[email protected]"; // 发送邮件的QQ
					String authcode = "fgoobvssrkuibjhe"; // 对于QQ的个人邮箱而言,密码使用的是客户端的授权码,而不是用户的邮箱密码
					Properties props = System.getProperties();
					props.put("mail.smtp.host", host);
					props.setProperty("mail.transport.protocol", "smtp"); // 发送邮件协议名称
					props.put("mail.smtp.auth", "true"); // 开启授权
					props.put("mail.smtp.user", from);
					props.put("mail.smtp.password", authcode);
					props.put("mail.smtp.port", "587"); // smtp邮件服务器的端口号,必须是587,465端口调试时失败
					props.setProperty("mail.smtp.ssl.enable", "true");

					Session session = Session.getDefaultInstance(props,
							new GMailAuthenticator("[email protected]",
									"fgoobvssrkuibjhe"));

					props.put("mail.debug", "true");

					MimeMessage message = new MimeMessage(session);
					Address fromAddress = new InternetAddress(from);
					Address toAddress = new InternetAddress(admin.getEmail());

					message.setFrom(fromAddress);
					message.setRecipient(Message.RecipientType.TO, toAddress);

					message.setSubject("注册成功确认邮件");
					message.setSentDate(new Date());
					//发送的链接包括其写入到数据库中的UUID,也就是链接localhost:8080/Login_Sys/ActivateServlet和UUID的拼接,#连接两个字符串
					//获取UUID
System.out.println(adminService.getUUID(admin));
					message.setContent("<h1>恭喜你注册成功,请点击下面的连接激活账户</h1><h3><a href='http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate.action?code="+adminService.getUUID(admin)+"'>http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate</a></h3>","text/html;charset=utf-8");
					Transport transport = session.getTransport();
					transport.connect(host, from, authcode);
					message.saveChanges();
					Transport.send(message);
					transport.close();

				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}

			} 
	    
//封装一个ModelAndView对象,提供转发视图的功能
	    ModelAndView modelAndView = new ModelAndView();
	    modelAndView.addObject("message", "增加管理员成功");
	    modelAndView.setViewName("sign_success");      //成功之后跳转到该界面,采用逻辑视图,必须要配置视图解析器
		return modelAndView;  //该方法一定要返回modelAndView
	}
 
public Session getSession() {
  Properties properties = System.getProperties();
  properties.setProperty("mail.smtp.host", host);
  properties.setProperty("mail.smtp.port", port);
  return Session.getDefaultInstance(properties);
}
 
源代码18 项目: Insights   文件: EmailUtil.java
public void sendEmail(Mail mail,EmailConfiguration emailConf, String emailBody) throws MessagingException,
																				IOException,UnsupportedEncodingException {

	Properties props = System.getProperties();
	props.put(EmailConstants.SMTPHOST, emailConf.getSmtpHostServer());
	props.put(EmailConstants.SMTPPORT, emailConf.getSmtpPort());
	props.put("mail.smtp.auth", emailConf.getIsAuthRequired());
	props.put("mail.smtp.starttls.enable", emailConf.getSmtpStarttlsEnable());

	// Create a Session object to represent a mail session with the specified
	// properties.
	Session session = Session.getDefaultInstance(props);
	MimeMessage msg = new MimeMessage(session);
	msg.addHeader(EmailConstants.CONTENTTYPE, EmailConstants.CHARSET);
	msg.addHeader(EmailConstants.FORMAT, EmailConstants.FLOWED);
	msg.addHeader(EmailConstants.ENCODING, EmailConstants.BIT);
	msg.setFrom(new InternetAddress(mail.getMailFrom(), EmailConstants.NOREPLY));
	msg.setReplyTo(InternetAddress.parse(mail.getMailTo(), false));
	msg.setSubject(mail.getSubject(), EmailConstants.UTF);
	msg.setSentDate(new Date());
	msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getMailTo(), false));
	MimeBodyPart contentPart = new MimeBodyPart();
	contentPart.setContent(emailBody, EmailConstants.HTML);

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(contentPart);

	String imageId="logoImage";
	String imagePath="/img/Insights.jpg";
	MimeBodyPart imagePart = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart);

	imageId="footerImage";
	imagePath="/img/FooterImg.jpg";
	MimeBodyPart imagePart_1 = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart_1);

	msg.setContent(multipart);

	try (Transport transport = session.getTransport();) {
		LOG.debug("Sending email...");

		transport.connect(emailConf.getSmtpHostServer(), emailConf.getSmtpUserName(),emailConf.getSmtpPassword());

		// Send the email.
		transport.sendMessage(msg, msg.getAllRecipients());
		LOG.debug("Email sent!");
	} catch (Exception ex) {
		LOG.error("Error sending email",ex);
		throw ex;
	} 

}
 
源代码19 项目: alfresco-repository   文件: ImapMessageTest.java
public void testEncodedFromToAddresses() throws Exception
{
    // RFC1342
    String addressString = "[email protected]";
    String personalString = "�?р�?ений Ковальчук";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");
    
    // Following method returns the address with quoted personal aka <["�?р�?ений Ковальчук"] <[email protected]>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // Starting from javax.mail 1.5.6 the address is folded at linear whitespace so that each line is no longer than 76 characters, if possible.
    String decodedAddress = MimeUtility.decodeText(MimeUtility.fold(6, address.toString()));
    
    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded", decodedAddress.equals(InternetAddress.toString(new Address[] {address})));
    
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");
    
    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);
    
    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);
    
    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());
    
    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);
    
    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}
 
源代码20 项目: alfresco-repository   文件: IncomingImapMessage.java
/**
 * Constructs {@link IncomingImapMessage} object based on {@link MimeMessage}
 * 
 * @param fileInfo - reference to the {@link FileInfo} object representing the message.
 * @param serviceRegistry - reference to serviceRegistry object.
 * @param message - {@link MimeMessage}
 * @throws MessagingException
 */
public IncomingImapMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry, MimeMessage message) throws MessagingException
{
    super(Session.getDefaultInstance(new Properties()));
    this.wrappedMessage = message; // temporary save it and then destroyed in writeContent() (to avoid memory leak with byte[] MimeMessage.content field)
    this.buildMessage(fileInfo, serviceRegistry);
}