Java发送邮件(二)

2014-11-24 03:29:14 · 作者: · 浏览: 4
l--setMessageWithAuthentica--MessagingException"+e);
} finally {
if(transport != null & transport.isConnected()){
transport.close();
}
}
}


public static void setMsg(String toMail, String title, String content)throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");
Session s = Session.getInstance(props);
s.setDebug(true);

MimeMessage message = new MimeMessage(s);
Transport transport = null;
try {
InternetAddress from = new InternetAddress("xxx@163.com");
message.setFrom(from);
InternetAddress to = new InternetAddress(toMail);
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(title);
message.setText(content);
message.setSentDate(new Date());
message.saveChanges();
transport = s.getTransport("smtp");
transport.connect("smtp.163.com", "xxx", "xxx");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
Loggers.error("发送邮件错误:SendMail--setMsg--AddressException:" + e);
} catch (MessagingException e) {
e.printStackTrace();
Loggers.error("发送邮件错误:SendMail--setMsg--MessagingException:" + e);
} finally {
if (transport != null & transport.isConnected()) {
transport.close();
}
}
}

public static void main(String[] args){
try {
SendMail.setMessageWithAuthentica("您的邮箱", "您的密码", "对方邮箱", "邮件内容", "邮件标题", "服务器地址");
} catch (Exception e) {
e.printStackTrace();
}
}
}

[java]
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class PopupAuthenticator extends Authenticator {
private String uname;//用户名

private String password;//密码

//属性方法
public String getUname() {
return uname;
}

public void setUname(String uname) {
this.uname = uname;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

//构造方法
public PopupAuthenticator() {

}

public PopupAuthenticator(String uname, String password) {
this.uname = uname;
this.password = password;
}

public PasswordAuthentication getPasswordAuthentication() {
String username = uname; //邮箱登录帐号
String pwd = password; //登录密码
return new PasswordAuthentication(username, pwd);
}
}


摘自 那年那月那天