📄 smtpclient.java
字号:
import java.io.IOException;
import java.util.Vector;
/**
* 该类封装SMTP协议
*/
public class SMTPClient {
private static final int PORT = 25;
private String localhost;
private MailConnection conn;
//构造方法,创建一个SMTP客户端对象。
public SMTPClient(String localhost) {
this.localhost = localhost;
if(this.localhost == null) {
this.localhost = "localhost";
}
}
//连接到邮件服务器
public void open(String host, String accounts, String password)
throws IOException, EMailException {
if(conn != null && conn.isConnection()) {
close();
}
conn = new MailConnection(host, PORT); //创建连接
try {
conn.receive();
execute("HELO " + localhost);
execute("AUTH LOGIN"); //认证
execute(getBase64String(accounts));
execute(getBase64String(password));
}
catch(EMailException eme) {
conn.close();
throw eme;
}
}
//关闭到邮件服务器的连接
public void close() throws IOException, EMailException {
execute("QUIT");
conn.close();
conn = null;
}
//发送邮件,subject是邮件的主题, msg是邮件的内容,recptList是收件人列表
public void send(String subject, String msg, String[] rcptList) throws IOException, EMailException {
EMailConfig config = EMailConfig.getInstance();
String sender = config.getEmailAddr(); //发件人
execute("MAIL FROM: <" + sender + ">");
StringBuffer sb = new StringBuffer();
for(int i=0; i<rcptList.length; i++) {
execute("RCPT TO: <" + rcptList[i] + ">");
if(sb.length() > 0) {
sb.append(",");
}
sb.append(rcptList[i]);
}
execute("DATA"); //发送邮件数据
//邮件由邮件头和邮件体两部分组成,邮件头以一个空白行结束。
//发送邮件头
conn.send("from: " + config.getEmailAddr());
conn.send("to: " + sb.toString());
conn.send("subject: " + subject);
conn.send("");//邮件头结束
//发送邮件体
conn.send(msg);
//邮件发送完毕
conn.send(".");
conn.receive();
}
//执行SMTP命令,返回结果
private String execute(String command) throws IOException, EMailException {
if(command != null) {
conn.send(command);
}
String line = conn.receive();
String result = line;
while((line.length() >= 4) && (line.charAt(3) == '-')) {
line = conn.receive();
result += line.substring(3);
}
char ch = result.charAt(0);
if(ch == '4' || ch == '5') {
throw new EMailException(result);
}
return result;
}
//返回参数str的Base64编码
private String getBase64String(String str) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
byte[] bytes = str.getBytes();
StringBuffer sb = new StringBuffer();
int len = bytes.length-bytes.length%3;
int data = 0;
for(int i=0; i<len; i+=3) {
data = (((int)bytes[i]) << 16) |
(((int)bytes[i+1]) << 8) |
bytes[i+2];
for(int j=18; j>=0; j -= 6) {
sb.append(alphabet[data>>j & 0x3F]);
}
}
if((bytes.length - len) == 2) {
data = (((int)bytes[len]) << 16) | (((int)bytes[len+1]) << 8);
for(int j=18; j>=6; j -= 6) {
sb.append(alphabet[data>>j & 0x3F]);
}
sb.append('=');
}
if((bytes.length - len) == 1) {
data = ((int)bytes[len]) << 16;
sb.append(alphabet[data>>18 & 0x3F]);
sb.append(alphabet[data>>12 & 0x3F]);
sb.append("==");
}
return sb.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -