下面列出了怎么用javax.mail.Store的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* This method delete all the sent mails. Can be used after a particular test class
*
* @throws MessagingException
* @throws IOException
*/
public static void deleteSentMails() throws MessagingException, IOException {
Properties props = new Properties();
props.load(new FileInputStream(new File(
TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
+ "smtp.properties")));
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());
Folder sentMail = store.getFolder("[Gmail]/Sent Mail");
sentMail.open(Folder.READ_WRITE);
Message[] messages =sentMail.getMessages();
Flags deleted = new Flags(Flags.Flag.DELETED);
sentMail.setFlags(messages,deleted,true);
sentMail.close(true);
store.close();
}
/**
* Delete all emails in the inbox.
*
* @param protocol protocol used to connect to the server
* @throws MessagingException if we're unable to connect to the store
*/
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
Folder inbox = null;
Store store = getConnection(user, protocol);
try {
inbox = store.getFolder(EMAIL_INBOX);
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.getMessages();
for (Message message : messages) {
message.setFlag(Flags.Flag.DELETED, true);
log.info("Deleted email Subject : " + message.getSubject());
}
} finally {
if (inbox != null) {
inbox.close(true);
}
if (store != null) {
store.close();
}
}
}
/**
* Check whether email received by reading the emails.
*
* @param protocol to connect to the store
* @param user whose mail store should be connected
* @param subject the subject of the mail to search
* @return
* @throws MessagingException when unable to connect to the store
*/
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
throws MessagingException {
Store store = getConnection(user, protocol);
Folder folder = store.getFolder(EMAIL_INBOX);
folder.open(Folder.READ_ONLY);
boolean isReceived = false;
Message[] messages = folder.getMessages();
for (Message message : messages) {
if (message.getSubject().contains(subject)) {
log.info("Found the Email with Subject : " + subject);
isReceived = true;
break;
}
}
return isReceived;
}
/**
* Static method to populate a {@link Index} with the messages in an {@link Store}
*/
public static Index populateFromStore(final Index index, Store store, int threads)
throws MessagingException, InterruptedException {
MessagingException messagingException = null;
final ExecutorService service = Executors.newFixedThreadPool(threads);
try {
index.setFolderSeparator(String.valueOf(store.getDefaultFolder().getSeparator()));
crawlFolders(store, index, store.getDefaultFolder(), service);
} catch (MessagingException ex) {
messagingException = ex;
}
service.shutdown();
service.awaitTermination(1, TimeUnit.HOURS);
if (index.hasCrawlException()) {
messagingException = index.getCrawlExceptions().iterator().next();
}
if (messagingException != null) {
throw messagingException;
}
return index;
}
ImapFolder( Store store,
String serverHost,
String folderName,
String userName,
String password ) {
this.isOpen = false;
this.store = store;
this.serverHost = serverHost;
this.folderName = folderName;
this.userName = userName;
this.password = password;
newMetaDataList = new ArrayList<MetaData>();
allMetaDataList = new ArrayList<MetaData>();
}
/**
* Close connection
* <b>Note</b>Internal method
* @throws MessagingException
*/
public void closeStoreConnection(
boolean storeConnected ) throws MessagingException {
if (storeConnected) {
// the folder is empty when the message is not loaded from IMAP server, but from a file
Folder imapFolder = message.getFolder();
if (imapFolder == null) {
imapFolder = partOfImapFolder; // in case of nested package but still originating from IMAP server
}
if (imapFolder != null) {
Store store = imapFolder.getStore();
if (store != null && store.isConnected()) {
// closing store closes and its folders
log.debug("Closing store (" + store.toString() + ") and associated folders");
store.close();
}
}
}
}
public int getEmailCountInFolder(String user, String password, String folderName) throws Exception {
if (server instanceof SmtpServer) {
throw new Exception("SMTP not applicable for reading folders");
}
Store store = server.createStore();
store.connect(user, password);
Folder newFolder = store.getFolder(folderName);
if (! newFolder.exists()) {
throw new Exception("No folder with name " + folderName);
}
newFolder.open(Folder.READ_ONLY);
return newFolder.getMessageCount();
}
public List<EMailMessageModel> getEmailsInFolder(String user, String password, String folderName) throws Exception {
if (server instanceof SmtpServer) {
throw new Exception("SMTP not applicable for reading folders");
}
Store store = server.createStore();
store.connect(user, password);
Folder newFolder = store.getFolder(folderName);
if (! newFolder.exists()) {
throw new Exception("No folder with name " + folderName);
}
newFolder.open(Folder.READ_ONLY);
List<EMailMessageModel> models = new ArrayList<>();
for (Message msg : newFolder.getMessages()) {
models.add(createMessageModel(msg));
}
return models;
}
/**
* Connects to email server with credentials provided to read from a given folder of the email application
*
* @param username Email username (e.g. [email protected])
* @param password Email password
* @param server Email server (e.g. smtp.email.com)
* @param emailFolder Folder in email application to interact with
*/
public EmailUtils(String username, String password, String server, EmailFolder emailFolder)
throws MessagingException {
Properties props = System.getProperties();
try {
props.load(new FileInputStream(new File("../src/test/resources/email.properties")));
} catch (Exception e) {
logger.error("Error occured while reading email properties ", e);
System.exit(-1);
}
Session session = Session.getInstance(props);
Store store = session.getStore("imaps");
store.connect(server, username, password);
folder = store.getFolder(emailFolder.getText());
folder.open(Folder.READ_WRITE);
}
/**
* 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;
}
/**
* Check mail folder for an email using subject.
*
* @param emailSubject Email subject
* @param folder mail folder to check for an email
* @param protocol protocol used to connect to the server
* @return whether mail received or not
* @throws MessagingException if we're unable to connect to the store
*/
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
GreenMailUser user) throws MessagingException {
boolean emailReceived = false;
Folder mailFolder;
Store store = getConnection(user, protocol);
try {
mailFolder = store.getFolder(folder);
mailFolder.open(Folder.READ_WRITE);
SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
Message[] messages = mailFolder.search(searchTerm);
for (Message message : messages) {
if (message.getSubject().contains(emailSubject)) {
log.info("Found the Email with Subject : " + emailSubject);
emailReceived = true;
break;
}
}
} finally {
if (store != null) {
store.close();
}
}
return emailReceived;
}
/**
* This method delete all the sent mails. Can be used after a particular test class
*
* @throws MessagingException
* @throws IOException
*/
public static void deleteSentMails() throws MessagingException, IOException {
Properties props = new Properties();
props.load(new FileInputStream(new File(
TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator
+ "smtp.properties")));
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());
Folder sentMail = store.getFolder("[Gmail]/Sent Mail");
sentMail.open(Folder.READ_WRITE);
Message[] messages =sentMail.getMessages();
Flags deleted = new Flags(Flags.Flag.DELETED);
sentMail.setFlags(messages,deleted,true);
sentMail.close(true);
store.close();
}
/**
* Check whether email received by reading the emails.
*
* @param protocol to connect to the store
* @param user whose mail store should be connected
* @param subject the subject of the mail to search
* @return
* @throws MessagingException when unable to connect to the store
*/
public static boolean isMailReceived(String protocol, GreenMailUser user, String subject)
throws MessagingException {
Store store = getConnection(user, protocol);
Folder folder = store.getFolder(EMAIL_INBOX);
folder.open(Folder.READ_ONLY);
boolean isReceived = false;
Message[] messages = folder.getMessages();
for (Message message : messages) {
if (message.getSubject().contains(subject)) {
log.info("Found the Email with Subject : " + subject);
isReceived = true;
break;
}
}
return isReceived;
}
/**
* delete all mails in the test mailbox, exceptions that may be produced during working with test
* mailbox:
*
* @throws MessagingException
*/
public void cleanMailBox() throws MessagingException {
Properties properties = System.getProperties(); // Get system properties
Session session = Session.getDefaultInstance(properties); // Get the default Session object.
Store store =
session.getStore("imaps"); // Get a Store object that implements the specified protocol.
store.connect(
host, user,
password); // Connect to the current host using the specified username and password.
Folder folder =
store.getFolder("inbox"); // Create a Folder object corresponding to the given name.
folder.open(Folder.READ_WRITE); // Open the Folder.
Message[] messages = folder.getMessages();
for (int i = 0, n = messages.length; i < n; i++) {
messages[i].setFlag(Flags.Flag.DELETED, true);
}
closeStoreAndFolder(folder, store);
}
@Override
public Collection<OutboundMessage> getMessagesToSend() throws Exception
{
List<OutboundMessage> retValue = new ArrayList<OutboundMessage>();
Store s = this.mailSession.getStore();
s.connect();
Folder inbox = s.getFolder(getProperty("mailbox_name", "INBOX"));
inbox.open(Folder.READ_WRITE);
for (Message m : inbox.getMessages())
{
OutboundMessage om = new OutboundMessage(m.getSubject(), m.getContent().toString());
om.setFrom(m.getFrom().toString());
om.setDate(m.getReceivedDate());
retValue.add(om);
// Delete message from inbox
m.setFlag(Flags.Flag.DELETED, true);
}
inbox.close(true);
s.close();
return retValue;
}
public JavaxMailStorage get() throws MessagingException {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "mstor");
properties.setProperty("mstor.mbox.metadataStrategy", "none");
properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
properties.setProperty("mstor.metadata", "disabled");
properties.setProperty("mstor.mozillaCompatibility", "enabled");
Session session = Session.getDefaultInstance(properties);
// /Users/flan/Desktop/Copy of Marie's Mail/Mail/Mail/mail.lean.to
File mailbox = new File(commandLineArguments.mailboxFileName);
if (!mailbox.exists()) {
throw new MessagingException("No such mailbox:" + mailbox);
}
Store store = session.getStore(
new URLName("mstor:" + mailbox.getAbsolutePath()));
store.connect();
return new ThunderbirdMailStorage(
logger,
new JavaxMailFolder(store.getDefaultFolder()),
statusParser);
}
public Store connectStore() throws MessagingException {
initProperties();
if (isSSLRequired()) {
return connectStoreSSL();
}
Properties properties = new Properties();
properties.put("mail." + getProtocol() + ".timeout", TIMEOUT);
properties.put("mail." + getProtocol() + ".connectiontimeout", TIMEOUT);
//properties.setProperty("mail.store.protocol", getProtocol());
Session session = Session.getInstance(properties, null);
Store store = session.getStore(getProtocol());
if (getIncomingPort() == 0) {
store.connect(getIncomingHost(), getUsername(), getPassword());
} else {
store.connect(getIncomingHost(), getIncomingPort(), getUsername(), getPassword());
}
return store;
}
/**
* Connect and verify the email settings.
*/
public void connect() {
Store store = null;
try {
log("Connecting email.", Level.FINER);
store = connectStore();
connectSession();
log("Done connecting email.", Level.FINER);
} catch (MessagingException messagingException) {
BotException exception = new BotException("Failed to connect - " + messagingException.getMessage(), messagingException);
log(exception);
throw exception;
} finally {
try {
if (store != null) {
store.close();
}
} catch (Exception ignore) {}
}
}
@Test
public void test2SendMessage2() throws Exception {
final Transport transport = session.getTransport(Providers.getSMTPProvider("makes_no_difference_here", true, true));
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test 1");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
transport.sendMessage(msg, new Address[] { new InternetAddress("[email protected]") });
final Store store = session.getStore("mock_pop3");
store.connect("[email protected]", null);
final Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Assert.assertEquals(1, inbox.getMessageCount());
Assert.assertNotNull(inbox.getMessage(1));
Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
inbox.close(false);
}
@Test
public void test3SendMessage() throws Exception {
Session.getDefaultInstance(getProperties());
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test 1");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
Transport.send(msg);
final Store store = session.getStore("mock_pop3");
store.connect("[email protected]", null);
final Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Assert.assertEquals(1, inbox.getMessageCount());
Assert.assertNotNull(inbox.getMessage(1));
Assert.assertEquals("Test 1", inbox.getMessage(1).getSubject());
inbox.close(false);
}
private void retrieveMail() throws NoSuchProviderException,
MessagingException, IOException {
Properties properties = new Properties();
Session session = Session.getInstance(properties);
Store store =
session.getStore(new URLName("pop3://john:[email protected]:"
+ PORT_POP + "/INBOX"));
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message[] messages = folder.getMessages();
assertEquals(1, messages.length);
Message message = messages[0];
assertEquals("Hello World!\r\n", message.getContent());
message.setFlag(Flags.Flag.DELETED, true);
folder.close(true);
store.close();
}
public static void parse(Message... messages) {
if (messages == null || messages.length == 0) {
System.out.println("没有任何邮件");
} else {
for (Message m : messages) {
parse(m);
}
// 最后关闭连接
if (messages[0] != null) {
Folder folder = messages[0].getFolder();
if (folder != null) {
try {
Store store = folder.getStore();
folder.close(false);// 参数false表示对邮件的修改不传送到服务器上
if (store != null) {
store.close();
}
} catch (MessagingException e) {
// ignore
}
}
}
}
}
protected void checkStoreForTestConnection(final Store store) {
if (!store.isConnected()) {
IMAPUtils.close(store);
throw new RuntimeException("Store not connected");
}
if (!store.getURLName().getUsername().toLowerCase().startsWith("es_imapriver_unittest")) {
IMAPUtils.close(store);
throw new RuntimeException("User " + store.getURLName().getUsername() + " belongs not to a valid test mail connection");
}
}
/**
* Check a particular email has received to a given email folder by email subject.
*
* @param emailSubject - Email emailSubject to find email is in inbox or not
* @return - found the email or not
* @throws ESBMailTransportIntegrationTestException - Is thrown if an error occurred while reading the emails
*/
public static boolean isMailReceivedBySubject(String emailSubject, String folder)
throws ESBMailTransportIntegrationTestException {
boolean emailReceived = false;
Folder mailFolder;
Store store = getConnection();
try {
mailFolder = store.getFolder(folder);
mailFolder.open(Folder.READ_WRITE);
SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
Message[] messages = mailFolder.search(searchTerm);
for (Message message : messages) {
if (message.getSubject().contains(emailSubject)) {
log.info("Found the email emailSubject : " + emailSubject);
emailReceived = true;
break;
}
}
return emailReceived;
} catch (MessagingException ex) {
log.error("Error when getting mail count ", ex);
throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex);
} finally {
if (store != null) {
try {
store.close();
} catch (MessagingException e) {
log.warn("Error when closing the store ", e);
}
}
}
}
@Override
public Integer call() throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect(host, username, password);
//System.out.println(store);
Folder f = store.getFolder(folder);
System.out.println(f.getName() + ":" + f.getUnreadMessageCount());
return f.getUnreadMessageCount();
}
public Mconn( ILogChannel log ) throws HopException, MessagingException {
super( log, MailConnectionMeta.PROTOCOL_IMAP, "junit", 0, "junit", "junit", false, false, "junit" );
store = Mockito.mock( Store.class );
inbox = Mockito.mock( Folder.class );
a = Mockito.mock( Folder.class );
b = Mockito.mock( Folder.class );
c = Mockito.mock( Folder.class );
when( a.getFullName() ).thenReturn( "A" );
when( b.getFullName() ).thenReturn( "B" );
when( c.getFullName() ).thenReturn( "C" );
when( a.exists() ).thenReturn( true );
when( b.exists() ).thenReturn( true );
when( c.exists() ).thenReturn( cCreated );
when( c.create( Mockito.anyInt() ) ).thenAnswer( new Answer<Boolean>() {
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable {
Object arg0 = invocation.getArguments()[ 0 ];
mode = Integer.class.cast( arg0 );
cCreated = true;
return true;
}
} );
when( inbox.getFolder( "a" ) ).thenReturn( a );
when( a.getFolder( "b" ) ).thenReturn( b );
when( b.getFolder( "c" ) ).thenReturn( c );
when( store.getDefaultFolder() ).thenReturn( inbox );
}
/**
* Valid activation email.
*
* @param mailHost
* example: imap.gmail.com
* @param mailUser
* login of mail box
* @param mailPassword
* password of mail box
* @param senderMail
* sender of mail box
* @param subjectMail
* subject of mail box
* @param firstCssQuery
* the first matching element
* @param conditions
* list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
* @throws TechnicalException
* is throws if you have a technical error (format, configuration, datas, ...) in NoraUi.
* Exception with message and with screenshot and with exception if functional error but no screenshot and no exception if technical error.
* @throws FailureException
* if the scenario encounters a functional error
*/
@Experimental(name = "validActivationEmail")
@RetryOnFailure(attempts = 3, delay = 60)
@Conditioned
@Et("Je valide le mail d'activation {string}(\\?)")
@And("I valid activation email {string}(\\?)")
public void validActivationEmail(String mailHost, String mailUser, String mailPassword, String senderMail, String subjectMail, String firstCssQuery, List<GherkinStepCondition> conditions)
throws FailureException, TechnicalException {
try {
final Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
final Session session = Session.getDefaultInstance(props, null);
final Store store = session.getStore("imaps");
store.connect(mailHost, mailUser, mailPassword);
final Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
final SearchTerm filterA = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
final SearchTerm filterB = new FromTerm(new InternetAddress(senderMail));
final SearchTerm filterC = new SubjectTerm(subjectMail);
final SearchTerm[] filters = { filterA, filterB, filterC };
final SearchTerm searchTerm = new AndTerm(filters);
final Message[] messages = inbox.search(searchTerm);
for (final Message message : messages) {
validateActivationLink(subjectMail, firstCssQuery, message);
}
} catch (final Exception e) {
new Result.Failure<>("", Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_MAIL_ACTIVATION), subjectMail), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
}
/**
* Reconnects if connection is closed.
* <b>Note</b>Internal method
* @return true if store re-connection is performed and this means that close should be closed after the work is done
* @throws MessagingException
*/
public boolean reconnectStoreIfClosed() throws MessagingException {
boolean storeReconnected = false;
// the folder is empty when the message is not loaded from IMAP server, but from a file
Folder imapFolder = message.getFolder();
if (imapFolder == null) {
imapFolder = this.partOfImapFolder;
} else {
partOfImapFolder = imapFolder; // keep reference
}
if (imapFolder != null) {
Store store = imapFolder.getStore();
if (store != null) {
if (!store.isConnected()) {
log.debug("Reconnecting store... ");
store.connect();
storeReconnected = true;
}
// Open folder in read-only mode
if (!imapFolder.isOpen()) {
log.debug("Reopening folder " + imapFolder.getFullName()
+ " in order to get contents of mail message");
imapFolder.open(Folder.READ_ONLY);
}
}
}
return storeReconnected;
}
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);
try {
MailConfiguration configuration = createConfiguration(parameters);
String timeoutVal = ConnectorOptions.extractOption(parameters, CONNECTION_TIMEOUT);
if (ObjectHelper.isEmpty(timeoutVal)) {
timeoutVal = Long.toString(DEFAULT_CONNECTION_TIMEOUT);
}
setConnectionTimeoutProperty(parameters, configuration, timeoutVal);
JavaMailSender sender = createJavaMailSender(configuration);
Session session = sender.getSession();
Store store = session.getStore(configuration.getProtocol());
try {
store.connect(configuration.getHost(), configuration.getPort(),
configuration.getUsername(), configuration.getPassword());
} finally {
if (store.isConnected()) {
store.close();
}
}
} catch (Exception e) {
ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
.detail("mail_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
.detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);
builder.error(errorBuilder.build());
}
return builder.build();
}
public void generateFolder(String user, String password, String folderName) throws Exception {
if (server instanceof SmtpServer) {
throw new Exception("SMTP not applicable for generating folders");
}
Store store = server.createStore();
store.connect(user, password);
Folder newFolder = store.getFolder(folderName);
if (! newFolder.exists()) {
newFolder.create(Folder.HOLDS_MESSAGES);
assertTrue(newFolder.exists());
}
newFolder.open(Folder.READ_WRITE);
assertTrue(newFolder.isOpen());
List<MimeMessage> msgs = new ArrayList<>();
for (int i = 1; i <= 5; ++i) {
// Use random content to avoid potential residual lingering problems
String subject = folderName + SPACE + HYPHEN + SPACE + GreenMailUtil.random();
String body = folderName + NEW_LINE + GreenMailUtil.random();
GreenMailUser greenUser = greenMail.setUser(user, password);
msgs.add(createTextMessage(greenUser.getEmail(), "Ben" + i + "@test.com", subject, body)); // Construct message
}
newFolder.appendMessages(msgs.toArray(new MimeMessage[0]));
assertEquals(msgs.size(), newFolder.getMessageCount());
}