网上很多,不过一般都是没有smtp验证的,下边是一段示例代码:
不能直接运行的,不过,可以看看里面关于验证的部分。
//发送邮件函数
public boolean sendmail(string mailto,string mailsubject,string mailbody){
//发送email
try {
//default account information
string smtpserver = “smtp.smtpserver.com”;
string smtpauth = “true”;
string smtpuser = “username”;
string smtppassword = “password”;
string from = “from@yourserver.com“;
string to = mailto;
string subject = mailsubject;
string text = mailbody;
java.util.resourcebundle resbundle;
resbundle = java.util.resourcebundle.getbundle(“mailinfo”,
locale.simplified_chinese);
if (resbundle != null) {
smtpserver = resbundle.getstring(“mail.smtp.host”);
smtpauth = resbundle.getstring(“mail.smtp.auth”);
smtpuser = resbundle.getstring(“mail.smtp.user”);
smtppassword = resbundle.getstring(“mail.smtp.password”);
from = resbundle.getstring(“mail.smtp.from”);
}
properties props = new properties();
session sendmailsession;
transport transport;
props.put(“mail.smtp.host”, smtpserver);
props.put(“mail.smtp.auth”, smtpauth);
if (“true”.equals(smtpauth)) {
//smtp服务器需要验证,用myauthertiactor来创建mail session
myauthenticator myauth = new myauthenticator(smtpuser, smtppassword);
sendmailsession = session.getinstance(props, myauth);
}
else {
sendmailsession = session.getinstance(props);
}
//debug
sendmailsession.setdebug(true);
message newmessage = new mimemessage(sendmailsession);
newmessage.setfrom(new internetaddress(from));
newmessage.setrecipient(message.recipienttype.to,
new internetaddress(mailto));
newmessage.setsubject(subject);
newmessage.setsentdate(new date());
newmessage.settext(text);
newmessage.savechanges();
transport = sendmailsession.gettransport(“smtp”);
transport.send(newmessage, newmessage.getallrecipients());
transport.close();
}
catch (exception mailex) {
system.err.println(“send mail error:” + mailex.getmessage());
return false;
}
return true;
}
//smtp需要验证时候的验证类
class myauthenticator
extends javax.mail.authenticator {
private string struser;
private string strpwd;
public myauthenticator(string user, string password) {
this.struser = user;
this.strpwd = password;
}
protected passwordauthentication getpasswordauthentication() {
return new passwordauthentication(struser, strpwd);
}
}