package com.asm;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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;
public class SendMail {
private static String host = ""; // smtp服务
private static String user = ""; // 用户
private static String pwd = ""; // 密码
private static String from = ""; // 发件人地
private static String from_tile = "定时任务"; //
private static String to = ""; // 收件人地
private static String subject = "定时发送邮件任务"; //邮件标题
static int i=0;
public static void sendEmail(String txt) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
// session.setDebug(false);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from, from_tile));
message.addRecipients(Message.RecipientType.TO,InternetAddress.parse(
to));
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
// 设置邮件的文本内�?
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(txt);
multipart.addBodyPart(contentPart);
// 添加附件
// BodyPart messageBodyPart = new MimeBodyPart();
// DataSource source = new FileDataSource(affix);
// 添加附件的内�?
// messageBodyPart.setDataHandler(new DataHandler(source));
// 添加附件的标�?
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
// messageBodyPart.setFileName("=?GBK?B?"+
// enc.encode(affixName.getBytes()()) + "?=");
// multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
// 保存邮件
message.saveChanges();
// 发�?邮件
Transport transport = session.getTransport("smtp");
// 连接服务器的邮箱
transport.connect(host, user, pwd);
// 把邮件发送出�?
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SendMail.sendEmail(""+i++);
}
}