使用javamail发信过程中的一些问题及解决方法

http://www.blogjava.net/TrampEagle/archive/2006/05/26/48326.html

今天在研究javamail发信的过程中,出现了一些小问题,现总结如下,以免后来者走些不必要的弯路,先把完整的能够正常运行的代码示例粘贴如下:
发邮件源代码:
package com.hyq.test;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class MailExample {

public static void main (String args[]) throws Exception {
   
    String host = "smtp.163.com";   //发件人使用发邮件的电子信箱服务器
    String from = "你自己的电子信箱";    //发邮件的出发地(发件人的信箱)
    String to = "收件人信箱";   //发邮件的目的地(收件人信箱)

// Get system properties
    Properties props = System.getProperties();

// Setup mail server
    props.put("mail.smtp.host", host);

// Get session
    props.put("mail.smtp.auth", "true"); //这样才能通过验证

MyAuthenticator myauth = new MyAuthenticator("你自己的电子信箱", "你自己的信箱密码");
    Session session = Session.getDefaultInstance(props, myauth);

//    session.setDebug(true);

// Define message
    MimeMessage message = new MimeMessage(session);

// Set the from address
    message.setFrom(new InternetAddress(from));

// Set the to address
    message.addRecipient(Message.RecipientType.TO,
      new InternetAddress(to));

// Set the subject
    message.setSubject("测试程序!");

// Set the content
    message.setText("这是用java写的发送电子邮件的测试程序!");

message.saveChanges();

Transport.send(message);
    
  }
}

校验发信人权限的方法
package com.hyq.test;

import javax.mail.PasswordAuthentication;

class MyAuthenticator
      extends javax.mail.Authenticator {
    private String strUser;
    private String strPwd;
    public MyAuthenticator(String user, String password) {
      this.strUser = user;
      this.strPwd = password;
    }

protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(strUser, strPwd);
    }
  }

注意:上面的事例仅为使用163信箱时发送电子邮件的方法,因为使用的host为:smtp.163.com,如源代码中:String
host = "smtp.163.com";  
//发件人使用发邮件的电子信箱服务器,如果使用其它的电子邮件发送,就必须在其邮件服务器上查找相应的电子邮件服务器,例如搜狐就要使用
smtp.sohu.com,具体情况具体对待,都可以从所使用的邮件服务器上获得的。如果没有使用host
,也就是说,没有进行props.put("mail.smtp.host",
host);设置,那么就会抛javax.mail.MessagingException: Could not connect to SMTP
host: localhost, port: 25;的异常。当然了,如果你没有正确配置,这个异常仍然会被抛出的。

有些邮件服务系统是不需要验证发件人的授权的,所以可以很简单的使用
    Session session = Session.getDefaultInstance(props, null);
             而不必使用
    props.put("mail.smtp.auth", "true"); 
    MyAuthenticator myauth = new MyAuthenticator("你自己的电子信箱", "你自己的信箱密码");
    Session session = Session.getDefaultInstance(props, myauth);

就可以发送电子邮件了,这个多为一些企事业单位的内部电子信箱系统。
但是对于很多门户网站上的电邮系统,如:163,sohu,yahoo等等,如果仍然简单的这样使用就会抛

com.sun.mail.smtp.SMTPSendFailedException: 553 authentication is required,smtp8,wKjADxuAyCAfmnZE8BwtIA==.32705S2

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)

at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)

at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)

at javax.mail.Transport.send0(Transport.java:169)

at javax.mail.Transport.send(Transport.java:98)

这样的异常,要求你必须进行授权校验,它的目的就是阻止他人任意乱发邮件,也算是为了减少垃圾邮件的出现吧。这时候,我们就要使用
    props.put("mail.smtp.auth", "true"); 
    MyAuthenticator myauth = new MyAuthenticator("你自己的电子信箱", "你自己的信箱密码");
    Session session = Session.getDefaultInstance(props, myauth);


里还有一个特别注意的事情:在你使用Session.getDefaultInstance时,一定要将   
props.put("mail.smtp.auth",
"true"); 置为true,它默认的是false,如果你没有做这一步,虽然你使用了
Session.getDefaultInstance(props, myauth);,你自己也确实    MyAuthenticator
myauth = new MyAuthenticator("你自己的电子信箱", "你自己的信箱密码");但是它仍然会抛出
com.sun.mail.smtp.SMTPSendFailedException: 553 authentication is required,smtp8,wKjADxJA2SBrm3ZEFv0gIA==.40815S2

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)

at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)

at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)

at javax.mail.Transport.send0(Transport.java:169)

at javax.mail.Transport.send(Transport.java:98)
这样的异常。我就在这一步费了好长时间,后来才发现了这个问题,很是郁闷。不过还好,总算解决了。

其实上面的做法只是比较简单的一种,也有很多其它的写法,如:
Properties props = System.getProperties();可以使用
Properties props = new Properties();来代替。

Transport.send(message);可以使用下面的代码来代替
      String username = "你的电子信箱用户名";
      String password = "你的电子信箱密码";
      message.saveChanges(); //    implicit with send()
      Transport transport = session.getTransport("smtp");
      transport.connect("mail.htf.com.cn", username, password);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
这种方法在同时发送多封电子邮件时比较有用。

还有一些具体的相关概念,可以查看相关的官方文档,在我查询资料时,发现了一篇文章写得相当仔细,可以加以参考:http://www.matrix.org.cn/resource/article/44/44101_JavaMail.html

另附上使用org.apache.commons.mail进行发电子邮件的示例:
import org.apache.commons.mail.SimpleEmail;
import org.apache.commons.mail.*;

public class TestCommon {
  public TestCommon() {
  }
  public static void main(String[] args){
    SimpleEmail email = new SimpleEmail();
    email.setHostName("smtp.163.com");//设置使用发电子邮件的邮件服务器
    try {
      email.addTo("收件人信箱");
      email.setAuthentication("发件人信箱","发件人信箱密码");
      email.setFrom("发件人信箱");
      email.setSubject("Test apache.commons.mail message");
      email.setMsg("This is a simple test of commons-email");
      email.send();
    }
    catch (EmailException ex) {
      ex.printStackTrace();
    }
  }
}

时间: 2025-01-05 09:18:41

使用javamail发信过程中的一些问题及解决方法的相关文章

LAMP系列之PHP编译过程中常见错误信息的解决方法

LAMP系列之PHP编译过程中常见错误信息的解决方法 在CentOS编译PHP5的时候有时会遇到以下的一些错误信息,基本上都可以通过yum安装相应的库来解决.以下是具体的一些解决办法: ******************************************************************************* checking for BZip2 support- yes checking  for BZip2 in default path- not foun

PHP编译过程中常见错误信息的解决方法

PHP编译过程中常见错误信息的解决方 checking for BZip2 support- yes checking for BZip2 in default path- not found configure: error: Please reinstall the BZip2 distribution Fix: yum install bzip2-devel checking for cURL support- yes checking if we should use cURL for

蘑菇街TeamTalk编译连接过程中遇到的问题及解决方法(iOS客户端)

今天浏览博文的时候,“蘑菇街开源的即时通讯框架,包括iOS.Android.Mac.Windows客户端和后台 Github源码下载地址:https://github.com/mogujie/TeamTalk ”这段话吸引了我,我就git clone https://github.com/mogujie/TeamTalk.git  到本地.一运行,没想到出现了很多问题.没办法,只能一个一个的解决,为了总结一下解决的思路以及过程,所以我写下了这片文章. 下面就详细介绍一下: 1. error: T

学习Android过程中遇到的问题及解决方法——电话监听

也许有时你会有这样一个需求:通电话时有一个重要的事需要记下来或者和一个陌生人特别是大骗子通话时,这是就想如果能把通话录下来就方便多了.(这才是我写这个代码的目的!!!) 在此过程中,犯了一个很大的错误.对电话状态还不熟悉就开始编程,使得我就算编写正确也出现各种bug. 先将代码列出来,供大家参考,然后解释错误和相关知识. activity_main.xml: 1 <?xml version="1.0" encoding="utf-8"?> 2 <L

ELK搭建过程中出现的问题与解决方法汇总

搭建过程中出现的问题 elasticsearch启动过程中报错[1] ERROR: [1] bootstrap checks failed [1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, d iscovery.seed_providers, cluster.initial_master_nodes] must be confi

zabbix &nbsp; 监控平台搭建过程中的报错与解决方法总结

1.php    option  post_max_size 2.php    option  max_execution_time 3.php    option  max_input_time 4.php    time   zone 5.php     bcmath 6.php     mbstring 解决1-3的报错修改php文件 vim  /etc/php.ini 修改相应参数为Required值 解决4报错:修改date.timezone=/Asia/Shanghai  注意去掉该

将Eclipse项目转换成AndroidStudio项目过程中遇到的问题以及解决方法

将Eclipse项目转换成AndroidStudio项目也不是第一次了,昨天转的时候遇到几个问题: 首先将项目导入androidstudio,导完后报错: 问题一: Error:java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: Error:Execution failed for task ':app:mergeDebugResources'.> Error: jav

linux使用过程中遇到的问题和解决方法

  测试过程中,出现以下错误,导致远程ssh连接不上,最终导致测试结果失败.系统日志如下: Sep 1 03:15:03 node3 avahi-daemon[5834]: Invalid response packet from host 193.168.17.222. Sep 1 03:15:03 node3 avahi-daemon[5834]: Invalid response packet from host 193.168.142.6. Sep 1 03:15:09 node3 av

配置solr过程中遇到的问题及解决方法

1.由于缺少solr源文件报错 4718 [coreLoadExecutor-4-thread-1] WARN  org.apache.solr.core.SolrResourceLoader  ? Can’t find (or read) directory to add to classloader: ../../../contrib/extraction/lib (resolved as: /home/apache-tomcat-6.0.37/solrhome/solr/collectio