使用SMTP发送163简单实现发送邮件(一)

 java中使用qq进行邮件发送邮件的时候,需要在qq邮箱中开启smtp,获取授权码,具体详情可以登录http://service.mail.qq.com/cgi-bin/help?id=28进行查看

尽量不要使用qq邮箱进行发送邮件。比较麻烦,后期持续更新qq发送

      注意:本教程在mac下进行操作的,倒入jar的同时不会像windows那样的麻烦,不需要手动把mail.jaractivation.jar文件添加到您的 CLASSPATH 中。要是windows别忘记添加路径!

使用163进行发送邮件:


第一步:导入activation.jar、mail.jar包到工程中

您可以从 Java 网站下载最新版本的JavaMail,打开网页右侧有个Downloads链接,点击它下载。

您可以从 Java 网站下载最新版本的JAF(版本 1.1.1)。

你也可以使用本站提供的下载链接:

JavaMail mail.jar 1.4.5

JAF(版本 1.1.1) activation.jar

第二步:上代码

packageEmploee;

importjava.io.*;

importjava.net.PasswordAuthentication;

importjava.util.*;

importjavax.mail.*;

importjavax.mail.internet.*;

importsun.security.util.Password;

importjavax.activation.*;

publicclassEmploee {

publicEmploee() {

//TODOAuto-generated constructor stub

}

publicstaticvoidmain(String[]args) {

//TODOAuto-generated methodstu

Stringto="对方的邮箱账户";//对方的邮箱账户

Stringfrome="自己的@163.com";

Stringpsd="密码";

// 指定发送邮件的主机为localhost

Stringhost="smtp.163.com";

// 获取系统属性

Propertiesproperties= System.getProperties();

// 设置邮件服务器

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

properties.put("mail.smtp.auth","true") ;//是否设置验证码

MyAuthenticatormyauth=newMyAuthenticator(frome,psd);

// 获取默认session对象

Sessionsession= Session.getDefaultInstance(properties,myauth);

try{

// 创建默认的 MimeMessage 对象

MimeMessagemessage=newMimeMessage(session);

// Set From: 头部头字段

message.setFrom(newInternetAddress(frome));

// Set To: 头部头字段

message.addRecipient(Message.RecipientType.TO,

newInternetAddress(to));

// Set Subject: 头部头字段

message.setSubject("这个是重要的邮件");

// 设置消息体

message.setText("我靠,qq邮箱好像需要进行验证!!!夜晚去郑大打球,我新学会一个姿势");

// 发送消息

Transport.send(message);

System.out.println("已发送!");

}catch(MessagingExceptionmex) {

mex.printStackTrace();

}

}

staticclassMyAuthenticator

extendsjavax.mail.Authenticator {

publicStringstrUser;

publicStringstrPwd;

publicMyAuthenticator(Stringuser, Stringpassword) {

this.strUser=user;

this.strPwd=password;

}

protectedjavax.mail.PasswordAuthentication getPasswordAuthentication() {

returnnewjavax.mail.PasswordAuthentication(strUser,strPwd);

}

}

}

你可能感兴趣的:(使用SMTP发送163简单实现发送邮件(一))