java mail api 学习

参考网址: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();

}

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值