關(guān)于使用javamail包發(fā)送郵件時(shí)編碼的解決問(wèn)題:推薦:java視頻教程
1. 在發(fā)送正文時(shí)指定正文編碼:
在發(fā)送郵件時(shí)使用
MimeBodyPart body = new MimeBodyPart(); body.setContent(content, "text/html;charset=GB2312");
注意此時(shí)的content編碼必須是所指定的編碼格式。
2. 在設(shè)置郵件標(biāo)題時(shí)也要指定標(biāo)題的編碼:
MimeMultipart mmp=new MimeMultipart(); mmp.setSubject(subject, "GB2312");
同上也要求subject的編碼和指定的編碼一致。
3. 發(fā)送正文時(shí)也可以在header中指定傳輸編碼:
body.setHeader("Content-Transfer-Encoding", "base64"); // 指定使用base64編碼
4. 例子:
import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class MailSender { public static void main(String[] args) { try { String host = "staff.tixa.com"; // smtp主機(jī) String username = "sample@staff.tixa.com"; // 認(rèn)證用戶名 String password = "sample"; // 認(rèn)證密碼 String from = "例子<sample@staff.tixa.com>"; // 發(fā)送者 String to = "toOne@staff.tixa.com, toAnother@staff.tixa.com"; // 接受者,用“,”分隔 String subject = "測(cè)試?yán)?quot;; String content = "僅僅是個(gè)供測(cè)試的例子。"; // 建立session Properties prop = new Properties(); prop.put("mail.smtp.host", host); prop.put("mail.smtp.auth", "true"); //是否需要認(rèn)證 Session session = Session.getDefaultInstance(prop, null); // 創(chuàng)建MIME郵件對(duì)象 MimeMessage mimeMsg = new MimeMessage(session); MimeMultipart mp = new MimeMultipart(); // 設(shè)置信息 mimeMsg.setFrom(new InternetAddress(from)); mimeMsg.setSubject(subject, "GB2312"); // ?。?!注意設(shè)置編碼 mimeMsg.setRecipients( Message.RecipientType.TO, InternetAddress.parse(to)); // 設(shè)置正文 BodyPart body = new MimeBodyPart(); body.setContent(content, "text/plain;charset=GB2312"); // ?。?!注意設(shè)置編碼 mp.addBodyPart(body); mimeMsg.setContent(mp); // 發(fā)送郵件 Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO)); transport.close(); } catch(Exception exp) { exp.printStackTrace(); } }