参考网址:http://blog.sina.com.cn/s/blog_6d3c1ec60100u98e.html
package cn.com.surekam.mail;
import java.util.Date;
import java.util.Properties;
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 SimpleSender {
public static void main(String args[]) {
try {
String smtpServer = "123.125.50.132";
String to = "328172228@qq.com";
String from = "liuxueping1734@163.com";
String subject = "test mail";
String body = "test mail";
String msgAttachment = "This is an attachment string!";
send(smtpServer, to, from, subject, body, msgAttachment);
} catch (Exception ex) {
System.out.println(ex.toString());
}
System.exit(0);
}
// 发送一封简单的邮件
public static void send(String smtpServer, String to, String from,
String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
// 发件人地址
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
// 收件人地址,可以是一个或多个。
msg.setSubject(subject);
// 邮件主题
msg.setSentDate(new Date());
// 发送时间
msg.setText(body);
// 邮件正文的内容
msg.setHeader("X-Mailer", "LOTONtechEmail");
Transport.send(msg);
System.out.println("Message sent OK.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 发送一封带有附件的邮件
public static void send(String smtpServer, String to, String from,
String subject, String body, String msgAttachment) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setHeader("X-Mailer", "LOTONtechEmail");
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body);
// 把前面定义的msgText中的文字设定为邮件正文的内容
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setText(msgAttachment, "utf-8");
// 创建附件部分
Multipart mp = new MimeMultipart();
// 创建Multipart
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// 把前面定义的正文和附件都添加到Multipart中
msg.setContent(mp);
// 添加 Multipart到Message中
Transport.send(msg);
System.out.println("Message sent OK.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}