java发邮件问题记录

 由于发送中文邮件报错,

     以163邮箱发送中文文本邮件为例:

     String host ="smtp.163.com";  

      Properties properties =new Properties();

        properties.setProperty("mail.smtp.host",host);

        properties.setProperty("mail.transport.protocol", "smtp");

        properties.setProperty("mail.smtp.auth","true");

        //properties.setProperty("mail.smtps.ssl.enable", "true");

//        properties.put("mail.smtp.ssl.enable", "true");

        Session session = Session.getDefaultInstance(properties);

        session.setDebug(true);

        Transport tf = session.getTransport();

        tf.connect(host,from,pwd);//pwd一定是用户授权码,如果是用户登录密码,会报错,如果自己不知道这个码是多少?可以先取消,然后在重新设置一下,就可以知道自己的授权码。

        MimeMessage message =new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));

        message.setSubject("主题主题");

        String temp ="主题主题主题主题主题主题主题主题主题主题";

        message.setContent(temp,"text/html;charset=UTF-8");//发现发送中文失败报554错,从163邮箱发送邮件报错,后来改成如下方法:

MimeBodyPart messageBodyPart =new MimeBodyPart();

messageBodyPart.setText(temp);

// 创建多重消息

Multipart multipart =new MimeMultipart();

multipart.addBodyPart(messageBodyPart);

message.setContent(multipart,"text/html;charset=UTF-8");

message.saveChanges();

tf.sendMessage(message,message.getAllRecipients());

tf.close();

这样就可以发送成功了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容