最近看了一些javamail的介绍,尝试写一个邮件服务器,出现很多疑问,在上网看过别人的代码后获益良多。于是在这写一下系统的实现和感想。
import java.util.*;
import javax.mail.*;
import java.io.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Email {
protected String to = null;
protected String subject = "Email Test";
protected String body = null;
public Email() {
super();
}
public void setTo(String to) {
this.to = to;
}
public void setBody(String body) {
this.body = body;
}
public void sendmail() {
try
{
String host = "smtp.163.net";
String from = "your name";
String to = "other email address";
String username = "your username";
String password = "your password";
this.body = "This is a test";
SmtpAuth sa=new SmtpAuth();
sa.getuserinfo(username,password);
Session session;
MimeMessage message;
Properties props = System.getProperties();
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host", host);
session = Session.getInstance(props, sa);
session.setDebug(true);
message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(body);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
message.setContent(mp);
message.setSentDate(new java.util.Date());
Transport transport = session.getTransport("smtp");
transport.connect("smtp.163.net",username,password);
transport.send(message);
}
catch (MessagingException e) {
System.out.println("error" + e.getMessage());
}
}
class SmtpAuth extends javax.mail.Authenticator {
private String user,password;
public void getuserinfo(String getuser,String getpassword){
user=getuser;
password=getpassword;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
return new javax.mail.PasswordAuthentication(user,password);
}
}
}
这里有几点要说明一下。
首先是内部类SmtpAuth。由于现今垃圾邮件的泛滥,所以在发送邮件时大部分邮件服务器都要求权限认证才能通过。将合法的用户名及密码作为参数构造一个SmtpAuth的对象,然后把这个对象传给session:session = Session.getInstance(props, sa); 只是这样做还是不行的,第一个属性参数要把验证设为真:props.put("mail.smtp.auth","true")。这样就OK了!
其次网上介绍了一些绕过权限的方法,但是我一直没能实现,还希望高手指点。
最后就是连接时的语句:transport.connect("smtp.163.net",username,password);,因为前面已经配置过了,这里可以不用任何参数连接。