您的位置:首页 > 编程语言 > Java开发

JAVAMAIL发送SMTP认证的邮件

2007-12-28 13:11 627 查看
网路上很多JAVAMAIL发送邮件的代码,比较杂乱,很多代码把附件,抄送都加上去了,对于初学JAVAMAIL的人可能不太有用,大多用到JAVAMAIL的程序,可能只是需要发发邮件(一般都是写一个自动发邮件的功能),这里给大家一个比较简单的需要认证的邮件发送的代码。

首先导入mail.jar和activation.jar这两个包。

import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMail {

public static void send(String body) throws MessagingException, AddressException, IOException {

String from = xxxxx@hp.com;

String to = yyyyy@alcatel-sbell.com;

String subject = "mail subject";

Properties props = System.getProperties();

props.put("mail.smtp.host", "smtp.hp.cpm");//这里请输入SMTP,可以使用新浪的。

props.put("mail.smtp.auth", "true");//这里写false的话,说明此邮件不需要验证

Session session = Session.getDefaultInstance(props,
new PasswordAuthenticator(from, "password"));

Message msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(from));

msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
false));

msg.setSubject(subject);

msg.setText(body);

msg.setSentDate(new Date());

Transport.send(msg);
}
}

class PasswordAuthenticator extends Authenticator {

private String username;

private String password;

public PasswordAuthenticator(String username, String password) {

this.username = username;

this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);
}

}

代码已经写好了 ,如果需要测试 ,直接调用send(String.....)方法就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: