Java Code Examples for javax.mail.internet.MimeMessage#setRecipient()

The following examples show how to use javax.mail.internet.MimeMessage#setRecipient() . 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: JavaMailSenderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void javaMailSenderWithMimeMessages() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage1, mimeMessage2);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(2, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage1, sender.transport.getSentMessage(0));
	assertEquals(mimeMessage2, sender.transport.getSentMessage(1));
}
 
Example 2
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void javaMailSenderWithMimeMessages() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage1, mimeMessage2);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(2, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage1, sender.transport.getSentMessage(0));
	assertEquals(mimeMessage2, sender.transport.getSentMessage(1));
}
 
Example 3
Source File: MailboxFolderTestCase.java    From javamail-mock2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddMessages() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg);

    Assert.assertEquals(1, mf.getMessageCount());
    Assert.assertNotNull(mf.getByMsgNum(1));
    Assert.assertEquals(msg.getSubject(), mf.getByMsgNum(1).getSubject());

    mf.add(msg);
    mf.add(msg);
    Assert.assertEquals(3, mf.getMessageCount());
    Assert.assertNotNull(mf.getByMsgNum(3));
    Assert.assertEquals(msg.getSubject(), mf.getByMsgNum(3).getSubject());

}
 
Example 4
Source File: SendingMailThroughAWSSESSMTPServer.java    From hellokoding-courses with MIT License 6 votes vote down vote up
void sendMail(String smtpServerHost, String smtpServerPort,  String smtpUserName, String smtpUserPassword, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", smtpServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        Transport transport = session.getTransport();
        transport.connect(smtpServerHost, smtpUserName, smtpUserPassword);
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
}
 
Example 5
Source File: SendingMailThroughGmailSMTPServer.java    From hellokoding-courses with MIT License 6 votes vote down vote up
void sendMail(String smtpServerHost, String smtpServerPort,  String smtpUserName, String smtpUserAccessToken, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", smtpServerPort);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        SMTPTransport transport = new SMTPTransport(session, null);
        transport.connect(smtpServerHost, smtpUserName, null);
        transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
}
 
Example 6
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void javaMailSenderWithMimeMessages() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage1, mimeMessage2);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(2, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage1, sender.transport.getSentMessage(0));
	assertEquals(mimeMessage2, sender.transport.getSentMessage(1));
}
 
Example 7
Source File: JamesMailetContext.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce
 *                   condition
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    Preconditions.checkArgument(mail.hasSender(), "Mail should have a sender");
    // This sends a message to the james component that is a bounce of the sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection<MailAddress> recipients = mail.getMaybeSender().asList();
    MailAddress sender = mail.getMaybeSender().get();

    reply.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getMaybeSender().asString()));
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return MailImpl.builder()
        .name("replyTo-" + mail.getName())
        .sender(sender)
        .addRecipients(recipients)
        .mimeMessage(reply)
        .build();
}
 
Example 8
Source File: TestSMTPServerTest.java    From OrigamiSMTP with MIT License 5 votes vote down vote up
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);
}
 
Example 9
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendMessage() throws Exception {
    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore(Providers.getIMAPProvider("makes_no_difference_here", true, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_WRITE);

    inbox.appendMessages(new MimeMessage[] { msg });

    Assert.assertEquals(4, inbox.getMessageCount());

    inbox.close(true);

}
 
Example 10
Source File: LiMeServerMailBox.java    From LiMe with MIT License 5 votes vote down vote up
public void sendSimpleMail(String recipient, String subject, String content) throws MessagingException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setContent(content, "text/html;charset=UTF-8");
    Transport.send(message);
}
 
Example 11
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testACLUnsupported() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore("mock_imap");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder test = defaultFolder.getFolder("test");

    final IMAPFolder testImap = (IMAPFolder) test;

    try {
        testImap.getACL();
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example 12
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void failedMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage1.setSubject("fail");
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

	try {
		sender.send(mimeMessage1, mimeMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(mimeMessage2, sender.transport.getSentMessage(0));
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 13
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void fFailedMimeMessage() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage1.setSubject("fail");
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

	try {
		sender.send(mimeMessage1, mimeMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(mimeMessage2, sender.transport.getSentMessage(0));
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 14
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
	final Session session = Session.getInstance(new Properties());
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals(session, sess);
			return super.getTransport(sess);
		}
	};
	sender.setSession(session);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setSubject("custom");
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
Example 15
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void javaMailProperties() throws MessagingException {
	Properties props = new Properties();
	props.setProperty("bogusKey", "bogusValue");
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals("bogusValue", sess.getProperty("bogusKey"));
			return super.getTransport(sess);
		}
	};
	sender.setJavaMailProperties(props);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
Example 16
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenameWithSubfolder() throws Exception {

    // final MockMailbox mb = MockMailbox.get("[email protected]");

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));

    final Store store = session.getStore("mock_imap");
    store.connect("[email protected]", null);
    final Folder root = store.getDefaultFolder();
    final Folder level1 = root.getFolder("LEVEL1");
    level1.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES);
    final Folder level2 = level1.getFolder("LEVEL2");
    level2.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES);
    level1.appendMessages(new Message[] { msg, msg });
    level2.appendMessages(new Message[] { msg });

    Assert.assertTrue(level1.exists());
    Assert.assertEquals("LEVEL1", level1.getFullName());
    Assert.assertEquals("LEVEL1", level1.getName());
    Assert.assertEquals(2, level1.getMessageCount());

    Assert.assertTrue(level2.exists());
    Assert.assertEquals("LEVEL1/LEVEL2", level2.getFullName());
    Assert.assertEquals("LEVEL2", level2.getName());
    Assert.assertEquals(1, level2.getMessageCount());
    Assert.assertEquals(2, root.list().length);

    // getFolder creates a store
    level1.renameTo(store.getFolder("LEVEL-1R"));

    // TODO really need a create?
    Assert.assertTrue(!store.getFolder("LEVEL1").exists());

    Assert.assertTrue(level1.exists());
    Assert.assertEquals("LEVEL-1R", level1.getFullName());
    Assert.assertEquals("LEVEL-1R", level1.getName());
    Assert.assertEquals(2, level1.getMessageCount());

    Assert.assertTrue(level2.exists());
    Assert.assertEquals("LEVEL-1R/LEVEL2", level2.getFullName());
    Assert.assertEquals("LEVEL2", level2.getName());
    Assert.assertEquals(1, level2.getMessageCount());

    Assert.assertEquals(2, root.list().length);
}
 
Example 17
Source File: BigAttachmentTest.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
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 18
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testDefaultFolder() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore("mock_imaps");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final Folder inbox = defaultFolder.getFolder("INBOX");

    inbox.open(Folder.READ_WRITE);

    Assert.assertEquals("[INBOX, test]", Arrays.toString(defaultFolder.list()));

    Assert.assertEquals(3, inbox.getMessageCount());
    Assert.assertNotNull(inbox.getMessage(1));

    inbox.close(true);

    Assert.assertEquals(3, inbox.getMessageCount());

    inbox.open(Folder.READ_WRITE);
    inbox.getMessage(1).setFlag(Flag.DELETED, true);

    inbox.close(true);
    inbox.open(Folder.READ_WRITE);
    Assert.assertEquals(2, inbox.getMessageCount());
    Assert.assertTrue(inbox instanceof UIDFolder);
    Assert.assertEquals(12L, ((UIDFolder) inbox).getUID(inbox.getMessage(1)));
    inbox.close(true);
}
 
Example 19
Source File: SendMail.java    From xunxian with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param targetMail  发送至的账号
 * @param title  发送的标题
 * @param content  发送的内容
 */
public void sendMail(String targetMail,String title,String content) {  
  try {  
  properties = new Properties();  
  //设置邮件服务器  
  properties.put("mail.smtp.host", "smtp.163.com");  
  //验证  
  properties.put("mail.smtp.auth", "true");  
  //根据属性新建一个邮件会话  
  mailSession = Session.getInstance(properties,  
  new Authenticator() {  
  public PasswordAuthentication getPasswordAuthentication() {  
  return new PasswordAuthentication("[email protected]",  
  "cccccc");  
  }  
  });  
  mailSession.setDebug(true);  
  //建立消息对象  
  mailMessage = new MimeMessage(mailSession);  
  //发件人  
  mailMessage.setFrom(new InternetAddress("[email protected]"));  
  //收件人  
  mailMessage.setRecipient(MimeMessage.RecipientType.TO,  
  new InternetAddress(targetMail));  
  //主题  
  mailMessage.setSubject(title);  
  //内容  
  mailMessage.setText(content);  
  //发信时间  
  mailMessage.setSentDate(new Date());  
  //存储信息  
  mailMessage.saveChanges();  
  //  
  trans = mailSession.getTransport("smtp");  
  //发送  
  trans.send(mailMessage);  
  } catch (Exception e) {  
	  new File().log("邮件发送失败异常捕获:"+e.getMessage());
  e.printStackTrace();  
  } finally {  
  }  
  }
 
Example 20
Source File: sendHtmlMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	Properties prop = new Properties();
	prop.setProperty("mail.debug", "true");
	prop.setProperty("mail.host", MAIL_SERVER_HOST);
	prop.setProperty("mail.transport.protocol", "smtp");
	prop.setProperty("mail.smtp.auth", "true");

	// 1、创建session
	Session session = Session.getInstance(prop);
	Transport ts = null;

	// 2、通过session得到transport对象
	ts = session.getTransport();

	// 3、连上邮件服务器
	ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);

	// 4、创建邮件
	MimeMessage message = new MimeMessage(session);

	// 邮件消息头
	message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
	message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
	message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
	message.setSubject("测试HTML邮件"); // 邮件的标题

	String htmlContent = "<h1>Hello</h1>" + "<p>显示图片<img src='cid:abc.jpg'>1.jpg</p>";
	MimeBodyPart text = new MimeBodyPart();
	text.setContent(htmlContent, "text/html;charset=UTF-8");
	MimeBodyPart image = new MimeBodyPart();
	DataHandler dh = new DataHandler(new FileDataSource("D:\\05_Datas\\图库\\吉他少年背影.png"));
	image.setDataHandler(dh);
	image.setContentID("abc.jpg");

	// 描述数据关系
	MimeMultipart mm = new MimeMultipart();
	mm.addBodyPart(text);
	mm.addBodyPart(image);
	mm.setSubType("related");
	message.setContent(mm);
	message.saveChanges();

	// 5、发送邮件
	ts.sendMessage(message, message.getAllRecipients());
	ts.close();
}