JavaMail发邮件以及邮件乱码之解决

JavaMail是Java平台常用的功能,这里记录下发邮件的功能,以及发出的邮件在接收时的编码问题。

 

1.jar包:mail.jar,425KB

2.代码:红色部分解决发件人名称和邮件主题的乱码问题

 private String fromName;
 private String username;
 private String password;
 private String smtpServer;
public void sendMail(InternetAddress[] addrArrTO, String subject,
   String content,File [] lstAttach) throws AddressException, MessagingException
 {
  // java.security.Security
  // .addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.host", smtpServer);
  // 获得邮件会话对象
  Session session = Session.getInstance(props);
  session.setDebug(true);

  Transport transport = (SMTPTransport) session.getTransport("smtp");
  transport.connect(null, username, password);

  MimeMessage mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
  try
  {
   mimeMsg.setFrom(new InternetAddress(username, MimeUtility
     .encodeText(fromName, "gb2312", "B")
));// 发件人邮件地址以及名称
   mimeMsg.setSubject(MimeUtility.encodeText(subject, "gb2312", "B"));// 主题
  }
  catch (UnsupportedEncodingException e)
  {
   mimeMsg.setFrom(new InternetAddress(username));// 发件人
  }

  if (addrArrTO.length > 0)
  {
   mimeMsg.setRecipients(Message.RecipientType.TO, addrArrTO);// 收件人
  }

  mimeMsg.setSentDate(new Date());// 发送日期
  // 正文
  Multipart mp = new MimeMultipart();
  BodyPart bp = new MimeBodyPart();
  bp.setContent("" + content, "text/html;charset=GB2312");
  mp.addBodyPart(bp);
  
  // 附件
  if (lstAttach.size() > 0)
  {
   for (File file : lstAttach)
   {
   BodyPart bpAttach = new MimeBodyPart();
   FileDataSource fileds = new FileDataSource(file);
   bpAttach.setDataHandler(new DataHandler(fileds));
   bpAttach.setFileName(fileds.getName());
   mp.addBodyPart(bpAttach);
   }
  }
  mimeMsg.setContent(mp);
  mimeMsg.saveChanges();

  transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
  transport.close();
 }

 

 

3.正文带图片

有两种方式:

一:将图片放在一个可以引用的服务器上,邮件内容引用该图片的URL。

import javax.mail.*;
import javax.mail.internet.*;

import java.util.Properties;

class SimpleMail1 {
    public static void main(String[] args) throws Exception{
        System.out.println("Sending mail...");
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.mymailserver.com");
        props.setProperty("mail.user", "myuser");
        props.setProperty("mail.password", "mypwd");

        Session mailSession = Session.getDefaultInstance(props, null);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject("HTML  mail with images");
        message.setFrom(new InternetAddress("me@sender.com"));
        message.setContent
          ("<h1>This is a test</h1>" 
           + "<img src=/"http://www.rgagnon.com/images/jht.gif/">", 
           "text/html");
        message.addRecipient(Message.RecipientType.TO,
             new InternetAddress("you@receiver.com"));

        transport.connect();
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
        }
}
二:将图片作为邮件附件,邮件正文引用该附件。
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import java.util.Properties;

class SimpleMail2 {
    public static void main(String[] args) throws Exception{
        System.out.println("Sending mail...");
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.mymailserver.com");
        props.setProperty("mail.user", "myuser");
        props.setProperty("mail.password", "mypwd");

        Session mailSession = Session.getDefaultInstance(props, null);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject("HTML  mail with images");
        message.setFrom(new InternetAddress("me@sender.com"));
        message.addRecipient(Message.RecipientType.TO,
             new InternetAddress("you@receiver.com"));

        //
        // This HTML mail have to 2 part, the BODY and the embedded image
        //
        MimeMultipart multipart = new MimeMultipart("related");

        // first part  (the html)
        BodyPart messageBodyPart = new MimeBodyPart();
        String htmlText = "<H1>Hello</H1><img src=/"cid:image/">";
        messageBodyPart.setContent(htmlText, "text/html");

        // add it
        multipart.addBodyPart(messageBodyPart);
        
        // second part (the image)
        messageBodyPart = new MimeBodyPart();
        DataSource fds = new FileDataSource
          ("C://images//jht.gif");
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.setHeader("Content-ID","<image>");

        // add it
        multipart.addBodyPart(messageBodyPart);

        // put everything together
        message.setContent(multipart);

        transport.connect();
        transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
        transport.close();
        }
}
阅读更多
个人分类: Java SE
想对作者说点什么? 我来说一句

javamail发送邮件 主题乱码解决

2016年09月02日 8KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭