欢迎使用CSDN-markdown编辑器

如果当我们是用java Mail进行邮件发送的时候,抛出了Could not connect to SMTP host: xx@xxx.com, port: 25的异常。
很有可能是你的服务器的运营商将25端口封禁了!
如果是,改成其他可用的smtp端口即可!如阿里云的465端口!

1、对应用程序配置邮件会话

javax.mail.Session保存邮件系统的配置属性和提供用户验证的信息,发送email首先要获取session对象。

(1)Session.getInstance(Java.util.Properties)获取非共享的session对象

(2)Session.getDefaultInstance(java.utilProperties)获取共享的session对象

两者都必须建立Properties prop=new Properties()对象;
注意:一般对单用户桌面应用程序使用共享Session对象。

用SMTP协议发送Email时通常要设置mail.smtp.host(mail.protocol.host协议特定邮件服务器名)属性。

prop.put(“mail.smtp.host”,“smtp.mailServer.com”);

Session mailSession=Session.getInstance(prop);

注意:在真正使用创建的过程中,往往会让我们验证密码,这是我们要写一个密码验证类。javax.mail.Authenticator是一个抽象类,我们要写MyAuthenticator的密码验证类,该类继承Authenticator实现:

protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(String userName, String password);
}

这时我们创建Session对象:

Session mailSession=Session.getInstance(prop,new MyAuthenticator(userName,Password));
并且要设置使用验证:prop.put(“mail.smtp.auth”,”true”);

使用 STARTTLS安全连接:prop.put(“mail.smtp.starttls.enable”,”true”);

2、配置邮件会话之后,要编写消息

要编写消息就要生成javax.mail.Message子类的实例或对Internet邮件使用javax.mail.interet.MimeMessage类。

(1)建立MimeMessage对象

MimeMessage扩展抽象的Message类,构造MimeMessage对象:

MimeMessage message=new MimeMessage(mailSession);

(2)消息发送者、日期、主题

message.setFrom(Address theSender);

message.setSentDate(java.util.Date theDate);

message.setSubject(String theSubject);

(3)设置消息的接受者与发送者(寻址接收)

setRecipient(Message.RecipientType type , Address theAddress)、setRecipients(Message.RecipientType type , Address[] theAddress)、addRecipient(Message.RecipientType type , Address theAddress)、addRecipients(Message.RecipientType type,Address[] theAddress)方法都可以指定接受者类型,但是一般用后两个,这样可以避免意外的替换或者覆盖接受者名单。定义接受者类型:
Message.RecipientType.TO:消息接受者

Message.RecipientType.CC:消息抄送者

Message.RecipientType.BCC:匿名抄送接收者(其他接受者看不到这个接受者的姓名和地址)

(4)设置消息内容

JavaMail基于JavaBean Activation FrameWork(JAF),JAF可以构造文本消息也可以支持附件。

设置消息内容时,要提供消息的内容类型—–即方法签名:

MimeMessage.setContent(Object theContent,String type);

也可以不用显式的制定消息的内容类型:MimeMessage.setText(String theText);

注意:建立地址javax.mail.InternetAddress toAddress=new InternetAddress(String address);

3、发送Email,这里以文本消息为例

javax.mail.Transport类来发送消息。这时Transport对象与相应传输协议通信,这里是SMTP协议。

Transport transport = mailSession.getTransport(“smtp”);//定义发送协议
transport.connect(smtpHost,“userName”, “UserPassword”);//登录邮箱
transport.send(message, message.getRecipients(RecipientType.TO));//发送邮件

public class SendMail {
@SuppressWarnings(“static-access”)
public static void sendMessage(String smtpHost, String from,
String fromUserPassword, String to, String subject,
String messageText, String messageType) throws MessagingException {
// 第一步:配置javax.mail.Session对象
System.out.println(“为” + smtpHost + “配置mail session对象”);

    Properties props = new Properties();  
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
    props.put("mail.smtp.auth", "true"); // 使用验证
    // props.put("mail.debug", "true");

    //-------当需使用SSL验证时添加,邮箱不需SSL验证时删除即可(测试SSL验证使用QQ企业邮箱)
    String SSL_FACTORY="javax.net.ssl.SSLSocketFactory"; 
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.port", "465"); //google使用465或587端口
    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true); 
    props.put("mail.smtp.ssl.socketFactory", sf);
    //-------
    Session mailSession = Session.getInstance(props,new MyAuthenticator(userName,UserPassword));  

    // 第二步:编写消息  
    System.out.println("编写消息from——to:" + from + "——" + to);  

    InternetAddress fromAddress = new InternetAddress(from);  
    InternetAddress toAddress = new InternetAddress(to);  

    MimeMessage message = new MimeMessage(mailSession);  

    message.setFrom(fromAddress);  
    message.addRecipient(RecipientType.TO, toAddress);  

    message.setSentDate(Calendar.getInstance().getTime());  
    message.setSubject(subject);  
    message.setContent(messageText, messageType);  

    // 第三步:发送消息  
    Transport transport = mailSession.getTransport("smtp");  
    transport.connect(smtpHost,"userName", UserPassword);  
    transport.send(message, message.getRecipients(RecipientType.TO));  
    System.out.println("message yes");  
}  

public static void main(String[] args) {  
    try {  
        SendMail.sendMessage("smtp.qq.com", "1234@qq.com",  
                "************", "3456@qq.com", "test",  
                "---------------test-----------",  
                "text/html;charset=utf-8");  
    } catch (MessagingException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }  
}  

}
class MyAuthenticator extends Authenticator{
String userName=”“;
String password=”“;
public MyAuthenticator(){

}  
public MyAuthenticator(String userName,String password){  
    this.userName=userName;  
    this.password=password;  
}  
 protected PasswordAuthentication getPasswordAuthentication(){     
    return new PasswordAuthentication(userName, password);     
 }   

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值