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.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 {
-
-
-
-
- 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);
-
-
- if (mailhost != null)
- props.put("mail.smtp.host ", mailhost);
-
-
- Session session = Session.getDefaultInstance(props, auth);
- if (debug)
- session.setDebug(true);
-
-
- 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() + "> ");
- MimeMultipart mp = new MimeMultipart("related ");
- 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;
-
-
-
-
-
-
-
-
- public class Email {
-
-
-
- private MimeMessage mimeMsg;
-
-
-
- private Session session;
-
-
-
- private Properties props;
-
-
-
- private String username;
-
-
-
- private String password;
-
-
-
- private Multipart mp;
-
-
-
-
-
-
-
- public Email(String smtp) {
- username = "";
- password = "";
-
- setSmtpHost(smtp);
-
- createMimeMessage();
- }
-
-
-
-
-
-
-
- public void setSmtpHost(String hostName) {
- System.out.println("设置系统属性:mail.smtp.host = " + hostName);
- if (props == null)
- props = System.getProperties();
- props.put("mail.smtp.host", hostName);
- }
-
-
-
-
-
-
- public boolean createMimeMessage() {
- try {
- System.out.println("准备获取邮件会话对象!");
-
- session = Session.getDefaultInstance(props, null);
- } catch (Exception e) {
- System.err.println("获取邮件会话对象时发生错误!" + e);
- return false;
- }
- System.out.println("准备创建MIME邮件对象!");
- try {
-
- mimeMsg = new MimeMessage(session);
-
- mp = new MimeMultipart();
- } catch (Exception e) {
- System.err.println("创建MIME邮件对象失败!" + e);
- return false;
- }
- return true;
- }
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
- public boolean setSubject(String mailSubject) {
- System.out.println("设置邮件主题!");
- try {
- mimeMsg.setSubject(mailSubject);
- } catch (Exception e) {
- System.err.println("设置邮件主题发生错误!");
- return false;
- }
- return true;
- }
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
-
- public boolean setFrom(String from) {
- System.out.println("设置发信人!");
- try {
- mimeMsg.setFrom(new InternetAddress(from));
- } catch (Exception e) {
- return false;
- }
- return true;
- }
-
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
- 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) {
-
-
-
-
-
-
-
-
-
-
- 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");
-
- themail.setNamePass("****@sina.com", "****");
-
- themail.sendout();
- }
- }
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/408390,如需转载请自行联系原作者