我正在编写一个用于从java发送邮件的独立代码。在这个程序中,我正在用户在控制台上获取所有信息。但这里的问题是身份验证部分。 我传递的是用户名和密码,实际上是邮件ID和发件人的密码。但它显示错误,可以引用非最终变量密码和发件人。
如果我最终完成,那么我无法从用户那里获取它。 Plz帮助我该怎么办?
package mypackage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
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 SendMailSSL {
public static void main(String[] args) throws IOException {
Properties props = new Properties();
String host="";
String port="";
String s_port="";
String to ="";
final String from="";
final String password="";
String subject="";
String context="";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("CONFIGURATION.... ");
System.out.println("mail.smtp.host=");
host = in.readLine();
System.out.println("mail.smtp.socketfactoryport=");
s_port=in.readLine();
props.put("mail.smtp.host", host);
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", s_port);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
System.out.println("mail.smtp.port=");
port=in.readLine();
props.put("mail.smtp.port", port);
System.out.println("AUTHENTICATION....");
System.out.println("Username=");
from=in.readLine();
System.out.println("Password=");
password = in.readLine();
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
String from = "";
String password="";
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from,password);
}
});
try {
System.out.println("Mail Sending Process..");
System.out.println("To=");
to=in.readLine();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
System.out.println("Subject=");
subject=in.readLine();
message.setSubject(subject);
System.out.println("Context=");
context = in.readLine();
message.setText(context);
Transport.send(message);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
System.out.println("in catch blk");
throw new RuntimeException(e);
}
}
}
你的帮助对我来说很宝贵。 提前致谢。
答案 0 :(得分:0)
关于final
关键字的问题在于它使您的变量写入一次/只读。它还意味着内部类可以引用它们。您应该做的是修改读取信息的代码,如下所示:
System.out.println("AUTHENTICATION....");
System.out.println("Username=");
final String from = in.readLine();
System.out.println("Password=");
final String password = in.readLine();
然后删除匿名Authenticator
实例中的变量声明。它现在将读取我们刚在外部代码块中声明的最终变量。有意义吗?
顺便问一下,你是否更习惯于用C语言编程?看起来你弄脏的是试图在开始逻辑之前声明所有变量,但这在java中根本不是必需的。实际上,它通常会使您的代码更难阅读!