import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
private String from;
private String to;
private String username;
private String password;
private String subject;
private String text;
private File file;
public SendMail(){
}
public SendMail(String from,String to,String username,String password){
this.from=from;
this.to=to;
this.username=username;
this.password=password;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public boolean send(){
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.163.com");
//props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.auth", true);
Session mailSession=Session.getDefaultInstance(props,null);
try{
Transport trans=mailSession.getTransport("smtp");
trans.connect("smtp.163.com",username,password);
// trans.connect();
Message newMessage=new MimeMessage(mailSession);
newMessage.setSubject(subject);
newMessage.setFrom(new InternetAddress(from));
/*
* 上传一个文件
* */
BodyPart fileBodyPart=new MimeBodyPart();
FileDataSource fds=new FileDataSource(file);
fileBodyPart.setDataHandler(new DataHandler(fds));
fileBodyPart.setFileName("a.wav");
Address addressTo[] = { new InternetAddress("406560484@qq.com")};
newMessage.setRecipients(Message.RecipientType.TO, addressTo);
newMessage.setText(text);
/*
* 将文件保存到Message中
* */
MimeMultipart multi = new MimeMultipart();
multi.addBodyPart(fileBodyPart);
newMessage.setContent(multi);
newMessage.saveChanges();
trans.sendMessage(newMessage, newMessage.getRecipients(Message.RecipientType.TO)); //发送邮件
trans.close();
return true;
}catch(Exception ex){
return false;
}
}
public static void main(String[] args){
SendMail sendmail=new SendMail("zxctch@163.com", "406560484@qq.com", "zxctch", "406560484");
//SendMail sendmail=new SendMail();
sendmail.setSubject("测试");
sendmail.setText("测试代码");
File file=new File("E://workspace//applet//bin//a.wav");
sendmail.setFile(file);
if(sendmail.send()){
System.out.println("send success");
}
else
System.out.println("send failed");
}
}