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();
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值