JAVA语言发送EMAIL的两种方法
方法一:使用类sun.net.smtp.SmtpClient
package mail;
import java.io.*;
import sun.net.smtp.*;
public class smtp{
String server,from,to;
public smtp(){
server="smtp.sina.com.cn";
from="wangtao_1979@sina.com";
to="happy_wangtao@avl.com.cn";
}
public void send(){
try{
SmtpClient smtp=new SmtpClient(server);
smtp.from(from);
smtp.to(to);
PrintStream out=smtp.startMessage();
out.println("Hello, wangtao!");
out.flush();
out.close();
smtp.closeServer();
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String args[]){
smtp s=new smtp();
s.send();
}
}
方法二:使用JavaMail
package mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import mail.*;
public class SimpleSender{
public static void send(String smtpserver,String to,String from,String subject,String body,String addfile){
try{
Properties props=System.getProperties();
props.put("mail.host",smtpserver);
props.put("mail.transport.protocol","smtp");
props.put("mail.smtp.host",smtpserver);
props.put("mail.smtp.auth","true");
EmailAutherticator emailautherticator=new EmailAutherticator("wangtao_1979","password");
Session session=Session.getDefaultInstance(props,(Authenticator)emailautherticator);
Transport transport=session.getTransport();
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to,false));
message.setSubject(subject);
MimeMultipart mmp=new MimeMultipart();
MimeBodyPart mbp1=new MimeBodyPart();
mbp1.setText(body);
mmp.addBodyPart(mbp1);
MimeBodyPart mbp2=new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(new FileDataSource(addfile)));
mbp2.setFileName((new FileDataSource(addfile)).getName());
mmp.addBodyPart(mbp2);
message.setContent(mmp);
transport.send(message);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
try{
String smtpserver="smtp.sina.com.cn";
String to="happy_wangtao@avl.com.cn";
String from="wangtao_1979@sina.com";
String subject="test";
String body="Hello, wangtao!";
String addfile="C:\\1.txt";
send(smtpserver,to,from,subject,body,addfile);
}catch(Exception e){
System.out.println(e);
}
}
}
自定义类Authenticator
package mail;
import javax.mail.*;
public class EmailAutherticator extends Authenticator{
private String username,password;
public EmailAutherticator(String username, String password){
super();
this.username=username;
this.password=password;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}