日期:2014-05-19 浏览次数:21001 次
import java.io.File; import java.util.Date; import java.util.Properties; import java.util.Vector; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class SendMailTest { public int sendMail(String host, String from, String username, String password, String to, String subject, String content, Vector appendFiles, boolean author) { try { Properties p = System.getProperties(); p.put("mail.smtp.host", host); p.put("mail.smtp.auth", author + ""); p.put("mail.smtp.localhost", "forceview"); Session session = Session.getDefaultInstance(p, new PopupAuthenticator(username, password)); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from));// 设置发送帐号 String[] tos = to.split(";"); InternetAddress[] sendTo = new InternetAddress[tos.length]; for (int i = 0; i < tos.length; i++) { sendTo[i] = new InternetAddress(tos[i]); } msg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);// 设置接收邮件的地址 msg.setSubject(subject, "utf-8");// 设置主题 msg.setSentDate(new Date());// 设置发送时间 Multipart mp = new MimeMultipart(); MimeBodyPart bp = new MimeBodyPart(); bp.setContent( "<meta http-equiv=Content-Type content=text/html; charset=utf-8>" + content, "text/html;charset=UTF-8"); mp.addBodyPart(bp); MimeBodyPart fp; String appendStrs = ""; if (appendFiles != null) { for (int i = 0; i < appendFiles.size(); i++) { fp = new MimeBodyPart(); appendStrs = appendFiles.get(i).toString(); String[] filenames = appendStrs.split("\\|"); if (new File(filenames[0]).exists()) { FileDataSource fds = new FileDataSource(filenames[0]); fp.setDataHandler(new DataHandler(fds)); fp.setFileName(MimeUtility.encodeText(filenames[1] + fds.getName(), "utf-8", "K")); mp.addBodyPart(fp); } } } msg.setContent(mp); msg.saveChanges(); Transport transport = session.getTransport("smtp");// 设置发送端口 transport.connect(host, username, password);// 连接邮件服务器 transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); return -1; } return 0; } class PopupAuthenticator extends Authenticator { private String username, password; public PopupAuthenticator(String username, String password) { this.username = username; this.password = password; } publ