我正在使用Java Mail API以及以下代码来阅读我的Gmail帐户中的电子邮件。
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class CheckMails {
public static void check(String host, String storeType, String user,
String password)
{
try {
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "myemai@gmail.com";// change accordingly
String password = "*******";// change accordingly
check(host, mailStoreType, username, password);
}
}
但我得到以下例外情况:
javax.mail.AuthenticationFailedException: [AUTH] Web login required: ` https://support.google.com/mail/bin/answer.py?answer=78754`
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
at javax.mail.Service.connect(Service.java:364)
at javax.mail.Service.connect(Service.java:245)
at CheckMails.check(CheckMails.java:26)
at CheckMails.main(CheckMails.java:66)
但我收到了一封来自我收件箱中的gmail的电子邮件 “我们最近阻止了尝试使用您的Google帐户的行为”。 如何使程序正常工作?
答案 0 :(得分:9)
使用
更改emailSession
变量
Session emailSession = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
正如Gmail所述
某些应用和设备使用安全性较低的登录技术 您的帐户更容易受到攻您可以关闭这些应用的访问权限, 我们建议使用,或者如果您想使用它们,请打开访问权限 风险。了解更多
只需点击下面的链接即可停用Gmail安全设置。它会正常运行。
的精彩文章