我正在构建一个应用程序,它接收用户的用户名和密码,并帮助发送邮件,使用Java编写相同的代码。我正在使用JavaMail API中的Authenticator类来完成身份验证。我正在使用此代码 -
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender{
GUI input = new GUI();
String username2= input.username.getText();
String password2 = input.password.getText();
public void SendMail(String ToAddress, String Name, String username1, String password1, String subject, String message, String salutation) {
String host = "smtp.gmail.com";
String from = "xxxx@xxxx.com";
String to = ToAddress;
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", 25);
props.put("mail.debug", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new GMailAuthenticator());
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(salutation+" "+Name+","+ "\n"+ message);
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
private static class GMailAuthenticator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username2, password2);
}
}
}
我创建了一个GUI类,它将用户名,密码,主题,邮件文本作为用户输入,我之前在代码本身中说明了这一点。 Netbeans在GmailAuthentication类中显示一个错误,即无法从静态上下文引用“非静态变量(如此处的username2和password2)。”
如何解决这个问题?我需要将用户名和密码作为GUI类的用户输入,并使用它们对Gmail进行身份验证。
答案 0 :(得分:2)
请注意,在这种情况下你don't really need an Authenticator;它只是让你的程序更复杂。
答案 1 :(得分:0)
而不是:
private static class GMailAuthenticator extends Authenticator {
尝试删除static
关键字:
private class GMailAuthenticator extends Authenticator {