我需要为我的项目提供帮助,我有一个方案,我将在我的邮件ID上获得一个验证码,我想获取该验证码并在脚本中使用。
请让我知道有人做了类似的事情,在此先感谢
答案 0 :(得分:0)
是的,我已经做到了。
一旦您从应用程序发送了OTP。您必须使用javax.mail
并必须编写代码以从邮箱读取提供的emailid的电子邮件。然后使用适当的正则表达式从获得的内容中提取OTP。
如果您正在使用Maven项目,请首先添加这些依赖项,否则必须在项目中添加相同的库
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
创建一个类并使用以下代码:
String hostName = "smtp.gmail.com";
String username = "email username"
String password = "email passeord"
int messageCount;
int unreadMsgCount;
String emailSubject;
Message emailMessage;
public MailReader() {
Properties sysProps = System.getProperties();
sysProps.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(sysProps, null);
Store store = session.getStore();
store.connect(hostName, username, password);
Folder emailInbox = store.getFolder("INBOX");
emailInbox.open(Folder.READ_WRITE);
messageCount = emailInbox.getMessageCount();
System.out.println("Total Message Count: " + messageCount);
unreadMsgCount = emailInbox.getNewMessageCount();
System.out.println("Unread Emails count:" + unreadMsgCount);
emailMessage = emailInbox.getMessage(messageCount);
emailSubject = emailMessage.getSubject();
Pattern linkPattern = Pattern.compile("href=\"(.*)\" target"); // here you need to define regex as per you need
Matcher pageMatcher =
linkPattern.matcher(emailMessage.getContent().toString());
while (pageMatcher.find()) {
System.out.println("Found OTP " + pageMatcher.group(1));
}
emailMessage.setFlag(Flags.Flag.SEEN, true);
emailInbox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}