javamail 邮件发送
package cn.itcast.javamail2; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Session; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class JavamailTest{ /** * @param args add by zxx ,Feb 5, 2009 */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");//设置邮箱验证
props.setProperty("mail.transport.protocol", "smtp");//设置发件服务器类型
props.setProperty("mail.host", "smtp.sina.com");//设置发件服务器
Session session = Session.getInstance(props);
session.setDebug(true); //设置debug调试用于打印出邮件发送过程信息
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("\"" + MimeUtility.encodeText("传智播客") + "\" <itcast_test@sina.com>"));//发件人 带有中文 在邮件中显示发件人为 传智播客"
msg.setSubject("你们的Java培训真的是最牛的吗?"); //邮件主题
msg.setReplyTo(new Address[]{new InternetAddress("lili@126.com")});//回复人 ,用于点击邮件的回复时回复的对象
msg.setRecipients(RecipientType.TO,InternetAddress.
parse(MimeUtility.encodeText("黎活明") + " <llm@itcast.cn>," + MimeUtility.encodeText("张孝祥") + " <zxx@itcast.cn>"));//收件人列表收件人显示 中文名字
MimeMultipart msgMultipart = new MimeMultipart("mixed"); msg.setContent(msgMultipart); MimeBodyPart attch1 = new MimeBodyPart(); MimeBodyPart attch2 = new MimeBodyPart(); MimeBodyPart content = new MimeBodyPart(); msgMultipart.addBodyPart(attch1); msgMultipart.addBodyPart(attch2); msgMultipart.addBodyPart(content); //附件一 DataSource ds1 = new FileDataSource("resource\\Java培训.txt"); DataHandler dh1 = new DataHandler(ds1 ); attch1.setDataHandler(dh1); attch1.setFileName(MimeUtility.encodeText("java培训.txt"));//设置附件名称 且可以是中文附件名称 //附件二 DataSource ds2 = new FileDataSource("resource\\slogo.gif" ); DataHandler dh2 = new DataHandler(ds2 ); attch2.setDataHandler(dh2); attch2.setFileName("slogo.gif");//设置附件名称 //邮件正文 显示内容 MimeMultipart bodyMultipart = new MimeMultipart("related"); content.setContent(bodyMultipart); MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart gifPart = new MimeBodyPart(); bodyMultipart.addBodyPart(htmlPart); bodyMultipart.addBodyPart(gifPart); //构建邮件图片 用于页面引用显示 DataSource gifds = new FileDataSource("resource\\logo.gif"); DataHandler gifdh = new DataHandler(gifds); gifPart.setDataHandler(gifdh); gifPart.setHeader("Content-Location", "http://www.itcast.cn/logo.gif");//设置附件头用于本邮件的引用 htmlPart.setContent("你们的Java培训真的是最牛的吗?大家都这么说,我想跟你们比试一下!这可是我自己用程序生成和发送的邮件哦!
<img src='http://www.itcast.cn/logo.gif'>", "text/html;charset=gbk");//其中引用了本邮件内的附件中的图像 msg.saveChanges();//保存修改生成最终邮件 OutputStream ips = new FileOutputStream("resource\\demo3.eml"); msg.writeTo(ips); ips.close();
Transport transport = session.getTransport();
transport.connect("smtp.sina.com", 25, "itcast_test", "123456");//建立连接
transport.sendMessage(msg,new Address[]{new InternetAddress("itcast_test@sohu.com")});//发送邮件
//transport.send(msg,new Address[]{new InternetAddress("itcast_test@sohu.com")});
transport.close();//关闭资源
}
}
package cn.itcast.javamail2; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import sun.misc.BASE64Encoder; public class Base64Util { /** * @param args add by zxx ,Dec 30, 2008 * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BASE64Encoder encoder = new BASE64Encoder(); System.out.println("please input user name:"); String username = new BufferedReader( new InputStreamReader(System.in)) .readLine(); System.out.println(encoder.encode(username.getBytes())); System.out.println("please input password:"); String password = new BufferedReader( new InputStreamReader(System.in)) .readLine(); System.out.println(encoder.encode(password.getBytes())); } }
直接发送邮件eml
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.sina.com");
Session session = Session.getInstance(props,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("itcast_test","123456");
}
}
);//验证发件人
session.setDebug(true);
Message msg = new MimeMessage(session,new FileInputStream("resouce\\demo3.eml"));//获得邮件的输入流 及session对象 Transport.send(msg,InternetAddress.parse("itcast_test@sohu.com"));//设置收件人地址 且此send方法为静态方法 做的操作为建立连接发送邮件及关闭相应资源
package com.golden.ex.ec.app.contract.service.impl; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Multipart; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.apache.commons.lang.StringUtils; import com.golden.ex.ec.app.contract.form.EmailAutherticator; import com.golden.tool.kit.PropertiesLoader; /** * 利用java.mail的邮件发送程序 */ public class SendMail { public static void main(String[] args) { String title = "titleTest";// 所发送邮件的标题 String from = "hb_duliang@126.com";// 从那里发送 String sendTo[] = { "78321189@qq.com" };// 发送到那里 // 邮件的文本内容,可以包含html标记则显示为html页面 String content = "mail test!!!!!!<br><a href=#>aaa</a>"; // 所包含的附件,及附件的重新命名 String fileNames[] = { "d:\\新建 文本文档 (2).txt,aa.txt","d:\\新建 文本文档.txt,bb.txt"}; try { send("标题", from, sendTo,"内容"); //send(title, sendTo, content); } catch (Exception ex) { ex.printStackTrace(); } } /** * 发送邮件(默认From),无附件 * @param subject 邮件标题 * @param to 发送到那里(字符串数组) * @param text 文件正文(支持HTML) * @throws Exception */ public static void send(String subject, String[] to, String text) throws Exception { send(subject,null,to,text); } /** * 发送邮件(默认From),带附件 * @param subject 邮件标题 * @param to 发送到那里(字符串数组) * @param text 文件正文(支持HTML) * @param filenames 附件文件存放的本地目录地址(字符串数组) * @throws Exception */ public static void send(String subject, String[] to, String text,String[] filenames) throws Exception { send(subject,null,to,text); } /** * 发送邮件(无附件),无附件 * @param subject 邮件标题 * @param from 从那里发送 admin@host.com * @param to 发送到那里(字符串数组) * @param text 文件正文(支持HTML) * @throws Exception */ public static void send(String subject, String from, String[] to, String text) throws Exception { send(subject,from,to,text,null); } /** * 发送邮件(默认字符集),带附件 * @param subject 邮件标题 * @param from 从那里发送 admin@host.com * @param to 发送到那里(字符串数组) * @param text 文件正文(支持HTML) * @param filenames 附件文件存放的本地目录地址(字符串数组) * @throws Exception */ public static void send(String subject, String from, String[] to, String text, String[] filenames) throws Exception { String mimeType = "text/html;charset=UTF-8"; send(subject,from,to,text,filenames,mimeType); } /** * 发送邮件 * @param subject 邮件标题 * @param from 从那里发送 admin@host.com * @param to 发送到那里(字符串数组) * @param text 文件正文(支持HTML) * @param filenames 附件文件存放的本地目录地址(字符串数组) * @param mimeType 文本格式,默认“text/html;charset=gb2312” * @throws Exception */ public static void send(String subject, String from, String[] to, String text, String[] filenames, String mimeType) throws Exception { PropertiesLoader pl = new PropertiesLoader("/config/Mail.properties"); String userid = pl.getProperty("mail.smtp.user"); String userpass = pl.getProperty("mail.smtp.pass"); String useremail = pl.getProperty("mail.smtp.from"); // 可以从配置文件读取相应的参数 Properties props = new Properties(); javax.mail.Session mailSession; // 邮件会话对象 javax.mail.internet.MimeMessage mimeMsg; // MIME邮件对象 props = java.lang.System.getProperties(); // 获得系统属性对象 /*props.put("mail.smtp.host",props.getProperty("mail.smtp.host")); // 设置SMTP主机 props.put("mail.smtp.auth", props.getProperty("mail.smtp.auth")); // 是否到服务器用户名和密码验证 */ props.put("mail.smtp.host", "smtp.126.com"); // 设置SMTP主机 props.put("mail.smtp.auth", "true"); // 是否到服务器用户名和密码验证 // 到服务器验证发送的用户名和密码是否正确 EmailAutherticator emailAutherticator = new EmailAutherticator( userid,userpass); /*EmailAutherticator emailAutherticator = new EmailAutherticator( "yqizhao2006", "556922@yqz");*/ // 设置邮件会话 mailSession = javax.mail.Session.getDefaultInstance(props, (Authenticator) emailAutherticator); // 设置传输协议 javax.mail.Transport transport = mailSession.getTransport("smtp"); // 设置from、to等信息 mimeMsg = new javax.mail.internet.MimeMessage(mailSession); if (null==from){ from =useremail;//"hb_duliang@126.com"; } if (!StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from,useremail); mimeMsg.setFrom(sentFrom); // 设置发送人地址 } InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); } mimeMsg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo); mimeMsg.setSubject(subject, "UTF-8"); MimeBodyPart messageBodyPart1 = new MimeBodyPart(); // messageBodyPart.setText(UnicodeToChinese(text)); messageBodyPart1.setContent(text, mimeType); Multipart multipart = new MimeMultipart();// 附件传输格式 multipart.addBodyPart(messageBodyPart1); if (null!=filenames&&filenames.length>0){ for (int i = 0; i < filenames.length; i++) { MimeBodyPart messageBodyPart2 = new MimeBodyPart(); // 选择出每一个附件名 String filename = filenames[i].split(",")[0]; String displayname = filenames[i].split(",")[1]; // 得到数据源 FileDataSource fds = new FileDataSource(filename); // 得到附件本身并至入BodyPart messageBodyPart2.setDataHandler(new DataHandler(fds)); // 得到文件名同样至入BodyPart // messageBodyPart2.setFileName(displayname); // messageBodyPart2.setFileName(fds.getName()); messageBodyPart2.setFileName(MimeUtility.encodeText(displayname)); multipart.addBodyPart(messageBodyPart2); } } mimeMsg.setContent(multipart); // 设置信件头的发送日期 mimeMsg.setSentDate(new Date()); mimeMsg.saveChanges(); // 发送邮件 Transport.send(mimeMsg); transport.close(); } }

浙公网安备 33010602011771号