1、引入相关的Jar包:
activation.jar、cos.jar、mail.jar
- <dependency>
- <groupId>com.alibaba.external</groupId>
- <artifactId>java.activation</artifactId>
- <version>1.1</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba.external</groupId>
- <artifactId>java.mail</artifactId>
- <version>1.4.3</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba.external</groupId>
- <artifactId>java.servlet</artifactId>
- <version>2.5</version>
- </dependency>
2、相关的发送代码
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Date;
- import java.util.Properties;
- import javax.mail.Address;
- import javax.mail.Message;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class SEND extends HttpServlet {
- public SEND() {
- super();
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- request.setCharacterEncoding("gb2312");
- String from = request.getParameter("from");
- String to = request.getParameter("to");
- String subject = request.getParameter("subject");
- String context = request.getParameter("context");
- // 确定要发送的邮件服务器的地址
- String mailserver = "d9e307714c5044f";
- // 设置邮件的传输协议
- try {
- Properties prop = System.getProperties();
- prop.put("mail.smtp.host", mailserver);
- // 建立邮件发送的连接
- Session session = Session.getDefaultInstance(prop, null);
- // 创建发送的信息的载体
- Message msg = new MimeMessage(session);
- // 设置相关的邮件属性
- msg.setFrom(new InternetAddress(from));
- // 点到点的发送
- msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
- /*
- * //群发 msg.setRecipients(Message.RecipientType.TO, new
- * InternetAddress[]{new InternetAddress(to),new
- * InternetAddress(to)}); //借助循环的标准发送
- */
- msg.setSubject(subject);
- msg.setSentDate(new Date());
- msg.setText(context);
- // 发送
- Transport.send(msg);
- } catch (Exception e) {
- }
- out.print("send ok");
- out.flush();
- out.close();
- }
- }
cmainserver下载:http://www.onlinedown.net/softdown/9044_2.htm
安装好了之后,执行如下步骤:开始->控制面板->管理工具->Internet 信息服务, 在启动的“Internet 信息服务”下面,找到“默认站点”, 右键点击“新建”->“虚拟目录”, 随便取个别名(比如mail), 在“目录”处浏览到cmainserver安装目录下面的webmail(比如:D:\ProgramFiles\CMailServer\webmail)。 在启动之后,即可通过http访问mail的网站了。
3、使用JavaMail在邮件中发送图片
本例参考:http://topic.csdn.net/t/20051012/09/4320650.html
带附件的参考:http://www.blogjava.net/sunfruit/archive/2006/10/24/77086.html
图片的保存与显示,参考:http://www.blogjava.net/PrettyBoyCyb/archive/2006/11/13/80922.html
javax.mail总结:http://lgcjar.javaeye.com/blog/511127
- package com.alibaba.annotation.client;
- import java.util.Properties;
- import java.util.Date;
- import javax.mail.*;
- import javax.mail.internet.*;
- import javax.activation.*;
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- sendhtml(args);
- }
- public static void sendhtml(String[] argv) throws Exception {
- String to = "q123456789@163.com ";
- String subject = "null ";
- String from = "abcdef@163.com ";
- String cc = null;
- String bcc = null;
- String mailhost = "smtp.163.com ";
- boolean debug = false;
- String username = "abcdef ";
- String password = "123456 ";
- Properties props = System.getProperties();
- props.put("mail.smtp.auth ", "true ");
- SMTPAuth auth = new SMTPAuth(username, password);
- // could use Session.getTransport() and Transport.connect()
- // assume we 're using SMTP
- if (mailhost != null)
- props.put("mail.smtp.host ", mailhost);
- // Get a Session object
- Session session = Session.getDefaultInstance(props, auth);
- if (debug)
- session.setDebug(true);
- // construct the message
- Message msg = new MimeMessage(session);
- if (from != null)
- msg.setFrom(new InternetAddress(from));
- else
- msg.setFrom();
- msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
- false));
- if (cc != null)
- msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(
- cc, false));
- if (bcc != null)
- msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(
- bcc, false));
- msg.setSubject(subject);
- MimeBodyPart mbp1 = new MimeBodyPart();
- String html = " <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"> "
- + " <html> "
- + " <head> <title> </title> </head> "
- + " <body> "
- + " <b> see the following jpg : it is a car! </b> <br> "
- + " <a href=http://www.a.com/a.jsp> hello </a> <br> "
- + " <IMG SRC=cid:7e2a34e1.jpg width=80% height=60%> <br> "
- + " <b> end of jpg </b> " + " </body> " + " </html> ";
- mbp1.setContent(html, "text/html ");
- FileDataSource fds = new FileDataSource("c:/7e2a34e1.jpg ");
- MimeBodyPart mbp2 = new MimeBodyPart();
- mbp2.setFileName(fds.getName());
- mbp2.setText("This is a beautiful car ! ");
- mbp2.setDataHandler(new DataHandler(fds));
- //mbp2.setHeader("Content-ID ", fds.getName());
- mbp2.setHeader( "Content-ID ", " < " + fds.getName() + "> ");
- MimeMultipart mp = new MimeMultipart("related ");// alternative
- mp.addBodyPart(mbp1);
- mp.addBodyPart(mbp2);
- msg.setContent(mp);
- msg.setSentDate(new Date());
- Transport.send(msg);
- System.out.println(mp.getCount());
- System.out.println("\nMail was sent successfully. ");
- }
- }
- class SMTPAuth extends javax.mail.Authenticator {
- private String user, password;
- public SMTPAuth(String u, String p) {
- user = u;
- password = p;
- }
- public void getuserinfo(String getuser, String getpassword) {
- user = getuser;
- password = getpassword;
- }
- protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
- return new javax.mail.PasswordAuthentication(user, password);
- }
- }
【注意】
1、经测试通过的程序
- package com.company.demoes;
- 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;
- /**
- * 本程序用java来实现Email的发送,所用到的协议为:SMTP,端口号为25;<br>
- * 方法:用Socket进行实现,打开客户端的Socket,并连接上服务器:<br>
- * 如:Socket sockClient = new Socket("smtp.qq.com",23);<br>
- * 这表示发件方连接的是QQ邮箱的服务器,端口号为23
- *
- */
- public class Email {
- /**
- * 整个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 Email(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) {
- /**
- *
- ************* 切切注意********
- *
- * 注意 用此程序发邮件必须邮箱支持smtp服务 在2006年以后申请的163邮箱是不支持的 我知道sina邮箱 sohu邮箱 qq邮箱支持
- * 但是sina和qq邮箱需要手工设置开启此功能 所以在测试时最好使用这三个邮箱 sina邮箱的smtp设置方法如下 登录sina邮箱
- * 依次点击 邮箱设置--->帐户--->POP/SMTP设置 将开启复选框选中 然后保存
- *
- ************* 切切注意********
- */
- Email themail = new Email("smtp.sina.com");// 这里以新浪邮箱为例子
- String mailbody = "hello!!!"; // 邮件内容
- themail.setNeedAuth(true);
- themail.setSubject("JAVA发邮件的测试");// 邮件主题
- themail.setBody(mailbody);// 邮件正文
- themail.setTo("****@qq.com");// 收件人地址
- themail.setFrom("tjwkj@sina.com");// 发件人地址
- themail.addFileAffix("d:\\temp\\aop.docx");// 附件文件路径,例如:C:/222.jpg,*注;"/"的写法;
- // 如果没有可以不写
- themail.setNamePass("****@sina.com", "****");// 发件人地址和密码
- // **改为相应邮箱密码
- themail.sendout();
- }
- }
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/408390,如需转载请自行联系原作者