我正在自动化一个网页,用于注册的otp将发送到电子邮件进行验证。我想从电子邮件中获取OTP并在文本字段中打印。
请咨询。
答案 0 :(得分:1)
下面的代码可用于从Outlook邮箱中提取OTP,类似的smtp可用于所有其他邮箱。
public static String OutlookMailReader(String mailFolderName,String emailSubjectContent, String emailContent, int lengthOfOTP) {
//mailFolderName(Eg- "INBOX"), emailSubjectContent(Eg- Mail for OTP),
emailContent(Eg- OTP is 111111), OTP length(Eg- 6)
String hostName = "smtp-mail.outlook.com";//change it according to your mail
String username = "****@***.com";//username
String password = "*******";
int messageCount;
int unreadMsgCount;
String emailSubject;
Message emailMessage;
String searchText=null ;
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 emailBox = store.getFolder(mailFolderName);
emailBox.open(Folder.READ_WRITE);
messageCount = emailBox.getMessageCount();
System.out.println("Total Message Count: " + messageCount);
unreadMsgCount = emailBox.getNewMessageCount();
System.out.println("Unread Emails count:" + unreadMsgCount);
for(int i=messageCount; i>(messageCount-unreadMsgCount); i--)
{
emailMessage = emailBox.getMessage(i);
emailSubject = emailMessage.getSubject();
if(emailSubject.contains(emailSubjectContent))
{
System.out.println("OTP mail found");
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(emailMessage.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String messageContent=emailContent;
String result = buffer.toString().substring(buffer.toString().indexOf(messageContent));
searchText = result.substring(messageContent.length(), messageContent.length()+lengthOfOTP);
System.out.println("Text found : "+ searchText);
emailMessage.setFlag(Flags.Flag.SEEN, true);
break;
}
emailMessage.setFlag(Flags.Flag.SEEN, true);
}
emailBox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
System.out.println("OTP Not found ");
}
return searchText;
}
说明: mailFolderName(例如,“ INBOX”),emailSubjectContent(例如,用于OTP的邮件), emailContent(例如OTP为111111),我的激活码为OTP长度(例如6)为6位数字。
该代码检查Outlook邮件,并检查带有主题(例如OTP邮件)的邮件的最近未读邮件。打开选定的邮件并返回OTP