兩個異常來到我的程序發送郵件.......問題在Java中
無法連接到本地主機,端口25
連接被拒絕
mail.java的代碼是---
package jMail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Mail {
private String to;
private String from;
private String message;
private String subject;
private String smtpServ;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSmtpServ() {
return smtpServ;
}
public void setSmtpServ(String smtpServ) {
this.smtpServ = smtpServ;
}
public Exception sendMail(){
try
{
Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host","localhost");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(message);
// -- Set some other header information --
msg.setHeader("MyMail", "Java Mail Test");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent to"+to+" OK.");
return null;
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Exception "+ex);
return ex;
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "[email protected]";
String password = "javamail";
return new PasswordAuthentication(username, password);
}
}
}
所以請告訴我該怎麼辦&爲什麼會出現這些異常&我該如何才能使用java localhost作爲主機發送郵件&。 .......................提前致謝。
您的計算機上是否運行SMTP服務器? – 2011-03-03 19:50:15
此外,您嘗試連接到本地主機,但使用Gmail憑據進行身份驗證。你的意思是通過Gmail的SMTP服務器發送郵件嗎? – dkarp 2011-03-04 04:09:32
我是新手,但我認爲smtp服務器正在我的m/c上運行,因爲當我使用smtp.gmail.com作爲主機時,異常Aries -javax.mail.AuthenticationFailedException。 – user643529 2011-03-04 09:58:55