java mail api学習
3921 ワード
参考URL:http://blog.sina.com.cn/s/blog_6 d 3 c 1 c 60100 u 98 e.
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 = "[email protected]";
String from = "[email protected]";
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();
}
}
}