一段带smtp认证的JavaMail代码。
发表于:2007-07-04来源:作者:点击数:
标签:
Properties props = System.getProperties(); props.put(mail.smtp.host, host); String mailNeedAuth = CatseyeConfig.getConfig(MailNeedAuth); String mailUser = CatseyeConfig.getConfig(MailUser); String mailPassword = CatseyeConfig.getConfig(Mail
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
String mailNeedAuth = CatseyeConfig.getConfig("MailNeedAuth");
String mailUser = CatseyeConfig.getConfig("MailUser");
String mailPassword = CatseyeConfig.getConfig("MailPassword");
if (mailNeedAuth.equals("1")) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
Session session = Session.getDefaultInstance(props, null);
javax.mail.Message msg = new MimeMessage(session);
InternetAddress[] toAddrs = null;
try {
if (recipients != null) {
toAddrs = InternetAddress.parse(recipients, false);
msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddrs);
} else {
throw new Exception("No recipient address specified");
}
if (sender != null) {
msg.setFrom(new InternetAddress(sender));
} else {
throw new Exception("No sender address specified");
}
if (subject != null) {
msg.setSubject(subject);
}
/*
BodyPart bp=new MimeBodyPart();
bp.setContent(body, "text/html");
Multipart mp=new MimeMultipart();
mp.addBodyPart(bp);
*/
//msg.setContent(mp);
msg.setContent(body, "text/html");
msg.setHeader("X-Mailer", "Catseye SMTP
Robot");
msg.setHeader("Content-Type", "text/html");
/*
msg.setDataHandler(new DataHandler(
new ByteArrayDataSource(body, "text/html")));
//msg.setText(body);
*/
Transport trans = session.getTransport("smtp");
trans.connect(host, mailUser, mailPassword);
trans.sendMessage(msg,
msg.getRecipients(
javax.mail.Message.RecipientType.TO));
原文转自:http://www.ltesting.net