
1、在发送正文时指定正文编码:
在发送邮件时使用
MimeBodyPart body = new MimeBodyPart(); body.setContent(content, "text/html;charset=GB2312");
注意此时的content编码必须是所指定的编码格式。
2、在设置邮件标题时也要指定标题的编码:
MimeMultipart mmp=new MimeMultipart(); mmp.setSubject(subject, "GB2312");
同上也要求subject的编码和指定的编码一致。
立即学习“Java免费学习笔记(深入)”;
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 mail发送邮件出现乱码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号