
關於使用javamail包發送郵件時編碼的解決問題:建議:java視訊教學
1. 在傳送正文時指定正文編碼:
在傳送郵件時使用
MimeBodyPart body = new MimeBodyPart(); body.setContent(content, "text/html;charset=GB2312");
注意此時的content編碼必須是所指定的編碼格式。
2. 在設定郵件標題時也要指定標題的編碼:
MimeMultipart mmp=new MimeMultipart(); mmp.setSubject(subject, "GB2312");
同上也要求subject的編碼和指定的編碼一致。
3. 發送正文時也可以在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主机
String username = "sample@staff.tixa.com"; // 认证用户名
String password = "sample"; // 认证密码
String from = "例子<sample@staff.tixa.com>"; // 发送者
String to = "toOne@staff.tixa.com, toAnother@staff.tixa.com"; // 接受者,用“,”分隔
String subject = "测试例子";
String content = "仅仅是个供测试的例子。";
// 建立session
Properties prop = new Properties();
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.auth", "true"); //是否需要认证
Session session = Session.getDefaultInstance(prop, null);
// 创建MIME邮件对象
MimeMessage mimeMsg = new MimeMessage(session);
MimeMultipart mp = new MimeMultipart();
// 设置信息
mimeMsg.setFrom(new InternetAddress(from));
mimeMsg.setSubject(subject, "GB2312"); // !!!注意设置编码
mimeMsg.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(to));
// 设置正文
BodyPart body = new MimeBodyPart();
body.setContent(content, "text/plain;charset=GB2312"); // !!!注意设置编码
mp.addBodyPart(body);
mimeMsg.setContent(mp);
// 发送邮件
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();
}
}更多java知識請關注java基礎教程欄。
以上是java郵件發送亂碼解決方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!