java邮件开发(三):解决附件名为乱码及显示友好名称

在上一篇文章(Java邮件开发(二):使用JMail发送一封图文并茂且包含附件的邮件(下) )中,我们学会了使用JavaMail发送一封复杂的邮件。

遗留的问题有以下两个:

1.附件的名称只能为英文,中文乱码

2.友好名称的显示。

我们使用163等邮箱发送邮件时,我们经常可以看到收件人一栏中会是:张益达 这种方式。在上一版本的代码中并没有使用这样的方式。

下面解决这两个问题

1. 对于中文乱码,是因为邮件要求所有的字符必须是ascII字符,中文字符当然不可以。因此我们只需要把我们的中文全部转码就可以了。

而JavaMail提供了这样一个类:MimeUtility。使用这个类的encodeText方法就可以对中文进行编码。

2. 对于显示友好名称,我们首先要了解收件人填写时的格式。格式一般为:友好名称 <邮箱地址>,如果有多个收件人要以逗号分割

如:张益达sohu ,张益达qq <554077931@qq.com>,张益达163

示例代码如下

 

package com.zyh.demo;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Address;
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;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
 
/**
  * 创建一个复杂的邮件,这个邮件包括一段正文和两个附件
  * 其中正文要包含一张图片
  * @author Administrator
  *
  */
public class Demo4 {
     
     public static void main(String[] args) throws Exception {
         Properties props = new Properties();
         props.setProperty( "mail.smtp.auth" , "true" );
         props.setProperty( "mail.transport.protocol" , "smtp" );
         
         Session session = Session.getInstance(props);
         session.setDebug( true );
         
         Message msg = new MimeMessage(session);
         /*邮件消息头设置*/
         //使用MimeUtility.encodeText()方法对中文进行编码(base64或QP)
         msg.setFrom( new InternetAddress( "\"" + MimeUtility.encodeText( "张益达sss" ) + "\" <zyh5540@163.com>" ));
         msg.setReplyTo( new Address[]{ new InternetAddress( "zyh5540@163.com" )});
         //友好名称和邮箱地址之间不要忘了有一空格,邮箱地址之间用逗号分隔
         //如:张益达sohu <zyh5540@sohu.com>,张益达qq <554077931@qq.com>,张益达163 <zyh5540@163.com>
         msg.setRecipients(RecipientType.TO,InternetAddress.parse(MimeUtility.encodeText( "张益达sohu" ) + " <zyh5540@sohu.com>,"
                 + MimeUtility.encodeText( "张益达qq" ) + " <554077931@qq.com>,"
                 + MimeUtility.encodeText( "张益达sina" ) + " <zyh5540@sina.com>,"
                 + MimeUtility.encodeText( "张益达163" ) + " <zyh5540@163.com>" ));
         msg.setSubject( "From 163 这是一封复杂邮件" );
         
         /*邮件消息内容设置,包括两个附件和一段正文*/
         Multipart msgPart = new MimeMultipart( "mixed" );
         msg.setContent(msgPart);       
         
         MimeBodyPart body = new MimeBodyPart();     //表示正文
         MimeBodyPart attach1 = new MimeBodyPart();  //表示附件1
         MimeBodyPart attach2 = new MimeBodyPart();  //表示附件2
         msgPart.addBodyPart(body);
         msgPart.addBodyPart(attach1);
         msgPart.addBodyPart(attach2);
         
         /*以下为设置正文*/
         /*正文是文字和图片混合的*/
         Multipart contentPart = new MimeMultipart( "related" );
         body.setContent(contentPart);
         MimeBodyPart content = new MimeBodyPart(); //文字
         MimeBodyPart img = new MimeBodyPart();     //图片
         contentPart.addBodyPart(content);
         contentPart.addBodyPart(img);
         
         DataSource fileds = new ByteArrayDataSource( new FileInputStream( "D:\\picture\\jpg\\touxiang.jpg" ), "image/jpeg" ); 
         DataHandler imgDataHandler = new DataHandler(fileds);
         img.setDataHandler(imgDataHandler);
         img.setHeader( "Content-ID" , "<touxiang.jpg>" );
         img.setFileName(MimeUtility.encodeText( "头像.jpg" ));
         //设置文字内容
         content.setContent( "<div style=" color:red;font-size:18px; ">从163发来的邮件</div>:我这里有一张图片<img style=" display: none; " src=" " alt=" touxiang " height=" 100px " width=" \"100px\" "><img alt=" 加载中... " title=" 图片加载中... " src=" http: //www.2cto.com/statics/images/s_nopic.gif">,好看吗?", "text/html;charset=utf-8");
         /*正文内容设置结束*/
         
         /*下面为设置附件*/
         attach1.setDataHandler( new DataHandler( new FileDataSource( "E:\\others\\firefox.txt" )));
         attach1.setFileName(MimeUtility.encodeText( "文件1.txt" ));
         attach2.setDataHandler( new DataHandler( new FileDataSource( "E:\\others\\java.txt" )));
         attach2.setFileName(MimeUtility.encodeText( "file文件2.txt" ));
         
         msg.saveChanges();
         
         OutputStream os = new FileOutputStream( "E:\\demo4.eml" );
         msg.writeTo(os);
         os.close();
         
         Transport trans = session.getTransport();
         trans.connect( "smtp.163.com" , 25 , "zyh5540" , "test" );
         trans.sendMessage(msg,msg.getAllRecipients());
java自动发邮件不错哦,美女程序猿web.xml文件 mailsenderservlet com.email.MailSenderServlet server smtp.163.com port 25 address username@163.com username username password ****** validate true time 5 1 servlet: package com.email; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MailSenderServlet extends HttpServlet { private MailSender sender; private Thread t; public void init() throws ServletException { sender = new MailSender(); sender.setRoot(root); String server = getInitParameter("server"); String port = getInitParameter("port"); String address = getInitParameter("address"); String username = getInitParameter("username"); String password = getInitParameter("password"); if (server == null || port == null || address == null || username == null || password == null) { System.out.println("系统文件web.xml错误:邮件发送程序初始化失败!"); return; } sender.setServer(server); sender.setPort(port); sender.setAddress(address); sender.setUsername(username); sender.setPassword(password); String time = getInitParameter("time"); if (time != null) { sender.setTime(Integer.parseInt(time)); } String validate = getInitParameter("validate"); if (validate != null) { sender.setValidate(Boolean.valueOf(validate).booleanValue()); } t = new Thread(sender); t.start(); //启动邮件发送线程 } public void destroy() { sender.stop(); //停止邮件发送线程 try { t.join(1000); if (t.isAlive()) { System.out.println("邮件发送线程未停止。"); } } catch (Exception e) {} } } 邮件发送程序 package com.email; import java.io.*; import java.sql.*; import java.util.*; import java.util.Date; import javax.activation.*; import javax.mail.*; import javax.mail.Message.*; import javax.mail.internet.*; /** * Copyright: Copyright (c) 2004 * @author flyxxxxx@163.com * @version 1.0 */ public class MailSender implements Runnable { private int time = 5 * 60 * 1000; //扫描数据库时间间隔 private boolean flag = true; //停止线程标记 private String server = "127.0.0.1"; //SMTP服务器地址 private String port = "25"; //SMTP服务器端口 private String address; //用于发送EMAIL的发送者地址 private String username; //发送者的用户名 private String password; //发送者的密码 private boolean validate = true; //邮件服务器是否要求验证 private File root = null; //WEB根目录 MailConfigManager manager = MailConfigManager.getInstance(); public MailSender() { } public void setAddress(String address) { this.address = address; } public void setPassword(String password) { this.password = password; } public void setPort(String port) { if (port != null && port.length() > 0) { this.port = port; } } public void setServer(String server) { this.server = server; } public void setUsername(String username) { this.username = username; } public void setValidate(boolean validate) { this.validate = validate; } public void setTime(int minute) { this.time = minute * 60 * 1000; } public void run() { long lastTime = new Date().getTime(); //保存前一次发送邮件的时间 while (flag) { //服务器停止时退出线程 long k = new Date().getTime() - lastTime; if (k time) { //超过设定时间间隔开始发送邮件 sendData(); lastTime = new Date().getTime(); } try { Thread.sleep(100); } catch (Exception e) {} } } public void stop() { flag = false; } /** * 检索数据库,并发送邮件 */ private void sendData() { ResultSet rs=null;//读取数据库数据 try { Session session = Session.getInstance(getProperties(), new Authentic()); while(flag) {//服务器停止时退出线程 String toAddress = null;//发送地址(从rs中得到) String subject = null;//邮件主题 String content = null ;//邮件内容 String file[] = null;//所有附件(绝对路径) sendMail(session, toAddress, subject, content, file);//发送邮件 } } catch (Exception e) { e.printStackTrace(); } finally { if(rs!=null){ try{ rs.close(); } catch(SQLException e){} } } } /** * 发送邮件 * @param session 会话 * @param toAddress 目的地址 * @param subject 邮件主题 * @param content 邮件内容(HTML) * @param files 邮件附件 * @return 是否发送成功 */ private boolean sendMail(Session session, String toAddress, String subject, String content, String[] files) { toAddress = "lijin@regaltec.com.cn"; try { Message rs = new MimeMessage(session); Address from = new InternetAddress(address); rs.setFrom(from); //发送地址 rs.setRecipient(RecipientType.TO, new InternetAddress(toAddress)); //接收地址 rs.setSubject(subject); //邮件主题 Multipart mp = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(content, "text/html; charset=GBK"); //邮件HTML内容 mp.addBodyPart(html); if (files != null && files.length > 0) { //邮件附件 for (int i = 0; i < files.length; i++) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(files[i]); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeWord(files[i]), "GBK", null)); mp.addBodyPart(mbp); } } rs.setContent(mp); //邮件全部内容 rs.setSentDate(new Date()); //发送时间 Transport.send(rs); //发送 return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 邮件会话属性 * @return 会话属性 */ private Properties getProperties() { Properties rs = new Properties(); rs.put("mail.smtp.host", server); rs.put("mail.smtp.port", port); rs.put("mail.smtp.auth", validate ? "true" : "false"); return rs; } public void setRoot(File root) { this.root = root; } class Authentic extends Authenticator { //验证密码 public Authentic() { } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值