类javax.mail.Session源码实例Demo

下面列出了怎么用javax.mail.Session的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: iaf   文件: MailSenderTestBase.java
@Test
public void mailWithPRC() throws Exception {
	String mailInput = "<email/>";

	appendParameters(sender);

	sender.configure();
	sender.open();

	sender.sendMessage(new Message(mailInput), session);
	Session mailSession = (Session) session.get("mailSession");
	assertEquals("localhost", mailSession.getProperty("mail.smtp.host"));

	MimeMessage message = (MimeMessage) mailSession.getProperties().get("MimeMessage");
	validateAuthentication(mailSession);
	compare("mailWithPRC.txt", message);
}
 
源代码2 项目: bobcat   文件: ImapConnector.java
protected void connectWithProtocol(String protocol) {
  try {
    Properties properties = new Properties();
    properties.setProperty("mail.store.protocol", protocol);
    Session session = Session.getDefaultInstance(properties, null);
    store = session.getStore(protocol);
    store.connect(configuration.getServer(), configuration.getPort(),
        configuration.getUsername(),
        configuration.getPassword());
    folder = store.getFolder(configuration.getFolderName());
    folder.open(Folder.READ_WRITE);

  } catch (MessagingException e) {
    LOG.error("error - cannot connect to mail server", e);
    throw new ConnectorException(e);
  }
}
 
源代码3 项目: rapidminer-studio   文件: MailSenderSMTP.java
@Override
public void sendEmail(String address, String subject, String content, Map<String, String> headers,
					  UnaryOperator<String> properties) throws Exception {
	Session session = MailUtilities.makeSession(properties);
	if (session == null) {
		LogService.getRoot().log(Level.WARNING, SESSION_CREATION_FAILURE, address);
	}
	MimeMessage msg = new MimeMessage(session);
	msg.setRecipients(Message.RecipientType.TO, address);
	msg.setFrom();
	msg.setSubject(subject, "UTF-8");
	msg.setSentDate(new Date());
	msg.setText(content, "UTF-8");

	if (headers != null) {
		for (Entry<String, String> header : headers.entrySet()) {
			msg.setHeader(header.getKey(), header.getValue());
		}
	}
	Transport.send(msg);
}
 
源代码4 项目: 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;
}
 
源代码5 项目: product-ei   文件: GreenMailServer.java
/**
 * Get the connection to a mail store
 *
 * @param user     whose mail store should be connected
 * @param protocol protocol used to connect
 * @return
 * @throws MessagingException when unable to connect to the store
 */
private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getInstance(props);
    int port;
    if (PROTOCOL_POP3.equals(protocol)) {
        port = 3110;
    } else if (PROTOCOL_IMAP.equals(protocol)) {
        port = 3143;
    } else {
        port = 3025;
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "localhost");
        props.put("mail.smtp.port", "3025");
    }
    URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword());
    Store store = session.getStore(urlName);
    store.connect();
    return store;
}
 
public void setReadyForEmail(String username, String password) {
	props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.socketFactory.port", "465");
	props.put("mail.smtp.socketFactory.class",
			"javax.net.ssl.SSLSocketFactory");
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.port", "465");
	
	Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});
	
	message = new MimeMessage(session);
}
 
源代码7 项目: appengine-tck   文件: MailHandlerServlet.java
/**
 * Stores subject and headers into memcache for test to confirm mail delivery.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    try {
        MimeMessage message = new MimeMessage(session, req.getInputStream());
        MimeProperties mp = new MimeProperties(message);

        List<String> headers = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        Enumeration e = message.getAllHeaderLines();
        while (e.hasMoreElements()) {
            String headerLine = (String) e.nextElement();
            headers.add(headerLine);
            sb.append("\n").append(headerLine);
        }
        log.info("HEADERS: " + sb.toString());

        mp.headers = headers.toString();
        TestBase.putTempData(mp);
    } catch (MessagingException me) {
        throw new IOException("Error while processing email.", me);
    }
}
 
源代码8 项目: jforgame   文件: EMailManager.java
/**
 * 创建一封只包含文本的简单邮件
 *
 * @param session     和服务器交互的会话
 * @param sendMail    发件人邮箱
 * @param receiveMail 收件人邮箱
 * @return
 * @throws Exception
 */
private MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String title, String content) throws Exception {
	// 1. 创建一封邮件
	MimeMessage message = new MimeMessage(session);

	// 2. From: 发件人
	message.setFrom(new InternetAddress(sendMail, "昵称", "UTF-8"));

	// 3. To: 收件人(可以增加多个收件人、抄送、密送)
	message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));

	// 4. Subject: 邮件主题
	message.setSubject(title, "UTF-8");

	// 5. Content: 邮件正文(可以使用html标签)
	message.setContent(content, "text/html;charset=UTF-8");
	// 6. 设置发件时间
	message.setSentDate(new Date());

	// 7. 保存设置
	message.saveChanges();

	return message;
}
 
源代码9 项目: camel-quarkus   文件: GoogleMailResource.java
private Message createMessage(String body) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);

    Profile profile = producerTemplate.requestBody("google-mail://users/getProfile?inBody=userId", USER_ID, Profile.class);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(TO, profile.getEmailAddress());
    mm.setSubject(EMAIL_SUBJECT);
    mm.setContent(body, "text/plain");

    Message message = new Message();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        mm.writeTo(baos);
        message.setRaw(Base64.getUrlEncoder().encodeToString(baos.toByteArray()));
    }
    return message;
}
 
源代码10 项目: iaf   文件: MailSenderTestBase.java
@Test
public void mailWithBase64Message() throws Exception {
	String mailInput = "<email>"
			+ "<recipients>"
				+ "<recipient type=\"to\" name=\"dummy\">[email protected]</recipient>"
			+ "</recipients>"
			+ "<subject>My Subject</subject>"
			+ "<from name=\"Me, Myself and I\">[email protected]</from>"
			+ "<message>VGhpcyBpcyBhIHRlc3QgZmlsZS4=</message>"
			+ "<messageType>text/plain</messageType>"
			+ "<replyTo>[email protected]</replyTo>"
			+ "<charset>UTF-8</charset>"
			+ "<messageBase64>true</messageBase64>"
		+ "</email>";

	sender.configure();
	sender.open();

	sender.sendMessage(new Message(mailInput), session);
	Session mailSession = (Session) session.get("mailSession");
	assertEquals("localhost", mailSession.getProperty("mail.smtp.host"));

	MimeMessage message = (MimeMessage) mailSession.getProperties().get("MimeMessage");
	validateAuthentication(mailSession);
	compare("mailWithBase64Message.txt", message);
}
 
源代码11 项目: javamail   文件: SmtpJmsTransportTest.java
@Test
public void testDoNotCheckFormHeader() throws Exception {
    Properties properties = new Properties();
    properties.setProperty("mail.smtpjms.validateFrom", "false");
    SmtpJmsTransport transport = new SmtpJmsTransport(Session.getInstance(properties), new URLName("jms"));
    Message message = Mockito.mock(Message.class);
    TransportListener listener = Mockito.mock(TransportListener.class);
    Address[] to = new Address[]{ new InternetAddress("[email protected]") };
    transport.addTransportListener(listener);
    transport.sendMessage(message, to);
    waitForListeners();
    ArgumentCaptor<TransportEvent> transportEventArgumentCaptor = ArgumentCaptor.forClass(TransportEvent.class);
    verify(listener).messageDelivered(transportEventArgumentCaptor.capture());
    TransportEvent event = transportEventArgumentCaptor.getValue();
    assertEquals(message, event.getMessage());
    assertEquals(TransportEvent.MESSAGE_DELIVERED, event.getType());
    assertArrayEquals(to, event.getValidSentAddresses());
}
 
源代码12 项目: camunda-bpm-mail   文件: PollMailConnectorTest.java
@Test
public void htmlMessage() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  Session session = greenMail.getSmtp().createSession();
  MimeMessage message = MailTestUtil.createMimeMessageWithHtml(session);

  GreenMailUtil.sendMimeMessage(message);

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails).hasSize(1);

  Mail mail = mails.get(0);
  assertThat(mail.getHtml()).isEqualTo("<b>html</b>");
  assertThat(mail.getText()).isEqualTo("text");
}
 
源代码13 项目: scava   文件: NntpUtil.java
public  static String getArticleBody(NNTPClient client, long articleNumber)
	throws IOException {
	String articleBody = null;
	//We convert the full message into a MIME message for getting exactly the text message clean
	Reader reader = (DotTerminatedMessageReader) client.retrieveArticle(articleNumber);
	if (reader != null) {
		InputStream inputStream = new ByteArrayInputStream(CharStreams.toString(reader).getBytes(Charsets.UTF_8));
		try {
			Session session = Session.getInstance(new Properties());	//For parsing the messages correctly
			MimeMessage message = new MimeMessage(session, inputStream);
			Object contentObject = message.getContent();
			if(!(contentObject instanceof MimeMultipart))
				articleBody = (String)contentObject;
			else
				articleBody = getBodyPart((MimeMultipart) contentObject);
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} else {
		return articleBody;
	}
	return articleBody;
}
 
源代码14 项目: 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; 
}
 
源代码15 项目: anyline   文件: MailUtil.java
/** 
 *  
 * @param fr		发送人姓名  fr		发送人姓名
 * @param to		收件人地址  to		收件人地址
 * @param title		邮件主题  title		邮件主题
 * @param content	邮件内容  content	邮件内容
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][content:{}]", 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; 
}
 
源代码16 项目: camunda-bpm-mail   文件: SendMailConnector.java
protected Message createMessage(SendMailRequest request, Session session) throws Exception {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(request.getFrom(), request.getFromAlias()));
    message.setRecipients(RecipientType.TO, InternetAddress.parse(request.getTo()));

    if (request.getCc() != null) {
      message.setRecipients(RecipientType.CC, InternetAddress.parse(request.getCc()));
    }
    if (request.getBcc() != null) {
      message.setRecipients(RecipientType.BCC, InternetAddress.parse(request.getBcc()));
    }

    message.setSentDate(new Date());
    message.setSubject(request.getSubject());

    if (hasContent(request)) {
      createMessageContent(message, request);
    } else {
      message.setText("");
    }

    return message;
  }
 
源代码17 项目: DotCi   文件: EmailNotifierBase.java
public MimeMessage createEmail(DynamicBuild build, BuildListener listener) throws AddressException, MessagingException {
    List<InternetAddress> to = getToEmailAddress(build, listener);

    String from = SetupConfig.get().getFromEmailAddress();
    Session session = Session.getDefaultInstance(System.getProperties());
    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));

    message.addRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));

    String subject = getNotificationMessage(build, listener);
    message.setSubject(subject);
    message.setText("Link to the build " + build.getAbsoluteUrl());
    return message;
}
 
/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth

    return mailSession;
}
 
@Test
public void sendAuthenticatedMessage() throws MessagingException, AlertException {
    TestProperties testProperties = new TestProperties();
    EmailProperties emailProperties = new EmailProperties(createEmailGlobalConfigEntity());

    FreemarkerTemplatingService freemarkerTemplatingService = new FreemarkerTemplatingService();
    EmailMessagingService emailMessagingService = new EmailMessagingService(emailProperties, freemarkerTemplatingService);

    Session mockSession = Mockito.mock(Session.class);
    Transport mockTransport = Mockito.mock(Transport.class);

    Mockito.doNothing().when(mockTransport).connect();
    Mockito.doNothing().when(mockTransport).close();
    Mockito.when(mockSession.getTransport(Mockito.anyString())).thenReturn(mockTransport);
    Mockito.when(mockSession.getProperties()).thenReturn(testProperties.getProperties());

    Message message = new MimeMessage(mockSession);
    Mockito.doNothing().when(mockTransport).sendMessage(Mockito.eq(message), Mockito.any());

    emailMessagingService.sendMessages(emailProperties, mockSession, List.of(message));
}
 
源代码20 项目: lutece-core   文件: MailUtil.java
/**
 * Send a calendar message.
 * 
 * @param mail
 *            The mail to send
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occurred during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
    Message msg = prepareMessage( mail, session );
    msg.setHeader( HEADER_NAME, HEADER_VALUE );

    MimeMultipart multipart = new MimeMultipart( );
    BodyPart msgBodyPart = new MimeBodyPart( );
    msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );

    multipart.addBodyPart( msgBodyPart );

    BodyPart calendarBodyPart = new MimeBodyPart( );
    calendarBodyPart.setContent( mail.getCalendarMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
                    + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
                    + AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
    calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
    multipart.addBodyPart( calendarBodyPart );

    msg.setContent( multipart );

    sendMessage( msg, transport );
}
 
源代码21 项目: james-project   文件: DKIMVerifyTest.java
private Mail process(String message) throws Exception {
    Mailet mailet = new DKIMVerify((new MockPublicKeyRecordRetriever(
        "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;",
        "selector", "example.com")));

    FakeMailetConfig mci = FakeMailetConfig.builder()
            .mailetName("Test")
            .mailetContext(FakeMailContext.defaultContext())
            .build();

    mailet.init(mci);

    Mail mail = FakeMail.builder()
        .name("test")
        .mimeMessage(new MimeMessage(Session
            .getDefaultInstance(new Properties()),
            new ByteArrayInputStream(message.getBytes())))
        .build();

    mailet.service(mail);
    return mail;
}
 
源代码22 项目: che   文件: MailSessionProvider.java
@VisibleForTesting
MailSessionProvider(Map<String, String> mailConfiguration) {
  if (mailConfiguration != null && !mailConfiguration.isEmpty()) {
    Properties props = new Properties();
    mailConfiguration.forEach(props::setProperty);

    if (Boolean.parseBoolean(props.getProperty("mail.smtp.auth"))) {
      final String username = props.getProperty("mail.smtp.auth.username");
      final String password = props.getProperty("mail.smtp.auth.password");

      // remove useless properties
      props.remove("mail.smtp.auth.username");
      props.remove("mail.smtp.auth.password");

      this.session =
          Session.getInstance(
              props,
              new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(username, password);
                }
              });
    } else {
      this.session = Session.getInstance(props);
    }
  } else {
    LOG.warn("Mail server is not configured. Cannot send emails.");
    this.session = null;
  }
}
 
源代码23 项目: glowroot   文件: AlertingService.java
public static void sendEmail(String centralDisplay, String agentRollupDisplay, String subject,
        List<String> emailAddresses, String messageText, SmtpConfig smtpConfig,
        @Nullable String passwordOverride, LazySecretKey lazySecretKey, MailService mailService)
        throws Exception {
    Session session = createMailSession(smtpConfig, passwordOverride, lazySecretKey);
    Message message = new MimeMessage(session);
    String fromEmailAddress = smtpConfig.fromEmailAddress();
    if (fromEmailAddress.isEmpty()) {
        String localServerName = InetAddress.getLocalHost().getHostName();
        fromEmailAddress = "[email protected]" + localServerName;
    }
    String fromDisplayName = smtpConfig.fromDisplayName();
    if (fromDisplayName.isEmpty()) {
        fromDisplayName = "Glowroot";
    }
    message.setFrom(new InternetAddress(fromEmailAddress, fromDisplayName));
    Address[] emailAddrs = new Address[emailAddresses.size()];
    for (int i = 0; i < emailAddresses.size(); i++) {
        emailAddrs[i] = new InternetAddress(emailAddresses.get(i));
    }
    message.setRecipients(Message.RecipientType.TO, emailAddrs);
    String subj = subject;
    if (!agentRollupDisplay.isEmpty()) {
        subj = "[" + agentRollupDisplay + "] " + subj;
    }
    if (!centralDisplay.isEmpty()) {
        subj = "[" + centralDisplay + "] " + subj;
    }
    if (agentRollupDisplay.isEmpty() && centralDisplay.isEmpty()) {
        subj = "[Glowroot] " + subj;
    }
    message.setSubject(subj);
    message.setText(messageText);
    mailService.send(message);
}
 
源代码24 项目: live-chat-engine   文件: SendMail.java
public static void main_send_by_concept() {
	
	String fromMail = "";
	String toMail = "";
	String subject = "Тестовый заголовок";
	String text = "<html><body><h1>Тест</h1><p>Тест отправки письма</body></html>";
	String username = "";
	String password = "";

	Properties props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.port", "587");
	
	Session session = Session.getInstance(props,
	  new javax.mail.Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
		}
	  });

	try {

		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(fromMail));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
		message.setSubject(subject);
		message.setText(text, "UTF-8", "html");

		Transport.send(message);

	} catch (MessagingException e) {
		throw new RuntimeException(e);
	}
	
}
 
protected void putMailInMailbox3(final int messages) throws MessagingException {

        for (int i = 0; i < messages; i++) {
            final MimeMessage message = new MimeMessage((Session) null);
            message.setFrom(new InternetAddress(EMAIL_TO));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS3));
            message.setSubject(EMAIL_SUBJECT + "::" + i);
            message.setText(EMAIL_TEXT + "::" + SID++);
            message.setSentDate(new Date());
            MockMailbox.get(EMAIL_USER_ADDRESS3).getInbox().add(message);
        }
        
        logger.info("Putted " + messages + " into mailbox "+EMAIL_USER_ADDRESS3);
    }
 
源代码26 项目: spring-analysis-note   文件: JavaMailSenderImpl.java
/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol.
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getSession()
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
	String protocol	= getProtocol();
	if (protocol == null) {
		protocol = session.getProperty("mail.transport.protocol");
		if (protocol == null) {
			protocol = DEFAULT_PROTOCOL;
		}
	}
	return session.getTransport(protocol);
}
 
源代码27 项目: spring-analysis-note   文件: SmartMimeMessage.java
/**
 * Create a new SmartMimeMessage.
 * @param session the JavaMail Session to create the message for
 * @param defaultEncoding the default encoding, or {@code null} if none
 * @param defaultFileTypeMap the default FileTypeMap, or {@code null} if none
 */
public SmartMimeMessage(
		Session session, @Nullable String defaultEncoding, @Nullable FileTypeMap defaultFileTypeMap) {

	super(session);
	this.defaultEncoding = defaultEncoding;
	this.defaultFileTypeMap = defaultFileTypeMap;
}
 
源代码28 项目: disconf   文件: SimpleMailSender.java
/**
 * @param mailInfo
 *
 * @return
 */
private static Message setCommon(MailSenderInfo mailInfo) throws MessagingException {

    //
    // 判断是否需要身份认证
    //
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }

    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);

    // 根据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());

    return mailMessage;

}
 
源代码29 项目: mireka   文件: PopMailImporter.java
private void importMails(GlobalUser user) throws MessagingException {
    logger.debug("Importing mail for " + user.getUsernameObject());
    Properties properties = new Properties();
    Session session = Session.getInstance(properties);
    Store store =
            session.getStore(new URLName("pop3://"
                    + user.getUsernameObject() + ":" + user.getPassword()
                    + "@" + remoteHost + ":" + +remotePort + "/INBOX"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message[] messages = folder.getMessages();
    int cSuccessfulMails = 0;
    // user name currently equals with the maildrop name, but this is
    // not necessarily true in general.
    String maildropName = user.getUsernameObject().toString();
    for (Message message : messages) {
        try {
            importMail(maildropName, message);
            message.setFlag(Flags.Flag.DELETED, true);
            cSuccessfulMails++;
        } catch (Exception e) {
            logger.error("Importing a mail for " + user.getUsernameObject()
                    + " failed", e);
        }
    }
    folder.close(true);
    store.close();
    totalMailCount += cSuccessfulMails;
    if (cSuccessfulMails > 0)
        totalUsersWithAtLeastOneMail++;
    logger.debug(cSuccessfulMails + " mails were imported for "
            + user.getUsernameObject());
}
 
源代码30 项目: james-project   文件: MimeMessageUtilsTest.java
@Test
public void buildNewSubjectShouldReplaceSubjectWhenPrefixIsNull() throws Exception {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    String prefix = null;
    String originalSubject = "original subject";
    String subject = "new subject";
    Optional<String> newSubject = new MimeMessageUtils(message).buildNewSubject(prefix, originalSubject, subject);

    assertThat(newSubject).contains(subject);
}
 
 类所在包
 同包方法