有两个类:
第一个MessageSender.java
第二个SendMailBean.java
- import java.util.Properties;
- import javax.activation.DataHandler;
- import javax.activation.FileDataSource;
- import javax.mail.BodyPart;
- 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 MessageSender {
- /**
- * 整个MIME邮件对象
- */
- private MimeMessage mimeMsg;
- /**
- * 专门用来发送邮件的Session会话
- */
- private Session session;
- /**
- * 封装邮件发送时的一些配置信息的一个属性对象
- */
- private Properties props;
- /**
- * 发件人的用户名
- */
- private String username;
- /**
- * 发件人的密码
- */
- private String password;
- /**
- * 用来实现附件添加的组件
- */
- private Multipart mp;
- /**
- * 发送参数初始化,有的服务器不需要用户验证,所以这里对用户名和密码进行初始化""
- *
- * @param smtp
- * SMTP服务器的地址,比如要用QQ邮箱,哪么应为:"smtp.qq.com",163为:"smtp.163.com"
- */
- public MessageSender(String smtp) {
- username = "";
- password = "";
- // 设置邮件服务器
- setSmtpHost(smtp);
- // 创建邮件
- createMimeMessage();
- }
- /**
- * 设置发送邮件的主机(JavaMail需要Properties来创建一个session对象。
- * 它将寻找字符串"mail.smtp.host",属性值就是发送邮件的主机);
- *
- * @param hostName
- */
- public void setSmtpHost(String hostName) {
- System.out.println("设置系统属性:mail.smtp.host = " + hostName);
- if (props == null)
- props = System.getProperties();
- props.put("mail.smtp.host", hostName);
- }
- /**
- * (这个Session类代表JavaMail 中的一个邮件session. 每一个基于
- * JavaMail的应用程序至少有一个session但是可以有任意多的session。 在这个例子中,
- * Session对象需要知道用来处理邮件的SMTP 服务器。
- */
- public boolean createMimeMessage() {
- try {
- System.out.println("准备获取邮件会话对象!");
- // 用props对象来创建并初始化session对象
- session = Session.getDefaultInstance(props, null);
- } catch (Exception e) {
- System.err.println("获取邮件会话对象时发生错误!" + e);
- return false;
- }
- System.out.println("准备创建MIME邮件对象!");
- try {
- // 用session对象来创建并初始化邮件对象
- mimeMsg = new MimeMessage(session);
- // 生成附件组件的实例
- mp = new MimeMultipart();
- } catch (Exception e) {
- System.err.println("创建MIME邮件对象失败!" + e);
- return false;
- }
- return true;
- }
- /**
- * 设置SMTP的身份认证
- */
- public void setNeedAuth(boolean need) {
- System.out.println("设置smtp身份认证:mail.smtp.auth = " + need);
- if (props == null)
- props = System.getProperties();
- if (need)
- props.put("mail.smtp.auth", "true");
- else
- props.put("mail.smtp.auth", "false");
- }
- /**
- * 进行用户身份验证时,设置用户名和密码
- */
- public void setNamePass(String name, String pass) {
- System.out.println("程序得到用户名与密码");
- username = name;
- password = pass;
- }
- /**
- * 设置邮件主题
- *
- * @param mailSubject
- * @return
- */
- public boolean setSubject(String mailSubject) {
- System.out.println("设置邮件主题!");
- try {
- mimeMsg.setSubject(mailSubject);
- } catch (Exception e) {
- System.err.println("设置邮件主题发生错误!");
- return false;
- }
- return true;
- }
- /**
- * 设置邮件内容,并设置其为文本格式或HTML文件格式,编码方式为UTF-8
- *
- * @param mailBody
- * @return
- */
- public boolean setBody(String mailBody) {
- try {
- System.out.println("设置邮件体格式");
- BodyPart bp = new MimeBodyPart();
- bp.setContent(
- "<meta http-equiv=Content-Type content=text/html; charset=UTF-8>"
- + mailBody, "text/html;charset=UTF-8");
- // 在组件上添加邮件文本
- mp.addBodyPart(bp);
- } catch (Exception e) {
- System.err.println("设置邮件正文时发生错误!" + e);
- return false;
- }
- return true;
- }
- /**
- * 增加发送附件
- *
- * @param filename
- * 邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常
- * @return
- */
- public boolean addFileAffix(String filename) {
- System.out.println("增加邮件附件:" + filename);
- try {
- BodyPart bp = new MimeBodyPart();
- FileDataSource fileds = new FileDataSource(filename);
- bp.setDataHandler(new DataHandler(fileds));
- // 发送的附件前加上一个用户名的前缀
- bp.setFileName(fileds.getName());
- // 添加附件
- mp.addBodyPart(bp);
- } catch (Exception e) {
- System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
- return false;
- }
- return true;
- }
- /**
- * 设置发件人地址
- *
- * @param from
- * 发件人地址
- * @return
- */
- public boolean setFrom(String from) {
- System.out.println("设置发信人!");
- try {
- mimeMsg.setFrom(new InternetAddress(from));
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- /**
- * 设置收件人地址
- *
- * @param to
- * 收件人的地址
- * @return
- */
- public boolean setTo(String to) {
- System.out.println("设置收信人");
- if (to == null)
- return false;
- try {
- mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO,
- InternetAddress.parse(to));
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- /**
- * 发送附件
- *
- * @param copyto
- * @return
- */
- public boolean setCopyTo(String copyto) {
- System.out.println("发送附件到");
- if (copyto == null)
- return false;
- try {
- mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC,
- InternetAddress.parse(copyto));
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- /**
- * 发送邮件
- *
- * @return
- */
- public boolean sendout() {
- try {
- mimeMsg.setContent(mp);
- mimeMsg.saveChanges();
- System.out.println("正在发送邮件....");
- Session mailSession = Session.getInstance(props, null);
- Transport transport = mailSession.getTransport("smtp");
- // 真正的连接邮件服务器并进行身份验证
- transport.connect((String) props.get("mail.smtp.host"), username,
- password);
- // 发送邮件
- transport.sendMessage(mimeMsg, mimeMsg
- .getRecipients(javax.mail.Message.RecipientType.TO));
- System.out.println("发送邮件成功!");
- transport.close();
- } catch (Exception e) {
- System.err.println("邮件发送失败!" + e.getMessage());
- e.printStackTrace();
- return false;
- }
- return true;
- }
- public static void main(String[] args) {
- MessageSender themail = new MessageSender("smtp.163.com");
- String mailbody = "手机停机了,写个程序发邮件,收到的话帮我下个java jdk6,你就在浏览器里面" +
- "输入http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u30-download-1377139.html,然后在下载列表里找jdk-6u30-windows-i586.exe,然后下载,thank you!!";
- themail.setNeedAuth(true);
- themail.setSubject("你好");
- themail.setBody(mailbody);
- themail.setTo("393769603@qq.com");
- themail.setFrom("tianbao004@163.com");
- //themail.addFileAffix("C:/CEPxDD0D.tmp");// 附件文件路径,例如:C:/222.jpg,*注;"/"的写法;
- themail.setNamePass("tianbao004@163.com","841104");
- themail.sendout();
- }
- }
- import java.util.Date;
- import java.util.Properties;
- import javax.mail.Message;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class SendMailBean {
- private String form;
- private String to;
- private String hostName;
- private String port;
- private String userName;
- private String password;
- private String subject;
- private String body;
- public String getForm() {
- return form;
- }
- public void setForm(String form) {
- this.form = form;
- }
- public String getTo() {
- return to;
- }
- public void setTo(String to) {
- this.to = to;
- }
- public String getHostName() {
- return hostName;
- }
- public void setHostName(String hostName) {
- this.hostName = hostName;
- }
- public String getPort() {
- return port;
- }
- public void setPort(String port) {
- this.port = port;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getSubject() {
- return subject;
- }
- public void setSubject(String subject) {
- this.subject = subject;
- }
- public String getBody() {
- return body;
- }
- public void setBody(String body) {
- this.body = body;
- }
- public boolean sendMail(){
- Properties props=new Properties();
- // props.put("mail.smtp.protocol","smtp");
- props.put("mail.smtp.host",hostName);
- props.put("mail.smtp.auth","true");
- props.put("mail.smpt.port",port);
- Session mailsession=Session.getInstance(props,null); //得到一个发送邮件的会话
- Message msg=new MimeMessage(mailsession);
- try{
- msg.setFrom(new InternetAddress(this.getForm()));
- msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(this.getTo()));
- msg.setSubject(this.getSubject());
- msg.setSentDate(new Date());
- msg.setText(this.getBody());
- Transport transport = mailsession.getTransport("smtp");
- transport.connect(this.getHostName(),this.getUserName(),this.getPassword());
- transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.TO));
- // System.out.println("邮件以成功发送到dushengjun@gmail.com");
- transport.close();
- return true;
- }catch(Exception e)
- {
- System.out.println("产生异常:"+e);
- return false;
- }
- }
- public static void main(String[] args) {
- System.out.println("正在准备发送.....");
- SendMailBean smb=new SendMailBean();
- smb.setUserName("tianbao004@163.com");
- smb.setForm("dushengjun@kingsoft.net");
- smb.setHostName("smtp.163.com");
- smb.setPassword("841104");
- smb.setPort("25");
- smb.setTo("284439843@qq.com");
- smb.setSubject("你好");
- smb.setBody("你好 Java");
- if(smb.sendMail())
- System.out.println("发送成功");
- else
- System.out.println("发送失败");
- }
- }
需要的jar包为:activation.jar dsn.jar imap.jar mailapi.jar pop3.jar smtp.jar