Java学习笔记(1)----Java中发送邮件
之前看过张孝祥讲解的邮件开发视频,只看了一小部分,那时候还是个小小小菜鸟,没看懂,以为这是个很复杂的技术。近来练习的一个小项目中用到了发送邮件的功能,参照网上的代码实现了这个功能。现在想想,这么简单呀!
实现此功能前你需要下载发送邮件所需要的jar包mail.jar,你也可以在此下载。
新建一个Java类文件MyAuthenticator.java,代码如下所示:
[java]
packagecom.ldfsoft.common;
importjavax.mail.Authenticator;
importjavax.mail.PasswordAuthentication;
public classMyAuthenticator extends Authenticator {
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
此类文件继承了mail.jar包中的Authenticator类。
接着又新建一个dto文件MailSenderDto.java,代码如下所示:
[java]
package com.ldfsoft.dto;
import java.util.Properties;
publicclass MailSenderDto {
// 发送邮件的服务器的IP和端口
private StringmailServerHost;
private StringmailServerPort = "25";
// 邮件发送者的地址
private StringfromAddress;
// 邮件接收者的地址
private StringtoAddress;
// 登陆邮件发送服务器的用户名和密码
private StringuserName;
private Stringpassword;
// 是否需要身份验证
privateboolean validate =false;
// 邮件主题
private Stringsubject;
// 邮件的文本内容
private Stringcontent;
// 邮件附件的文件名
private String[]attachFileNames;
/**
* 获得邮件会话属性
*/
public PropertiesgetProperties(){
Properties p = new Properties();
p.put("mail.smtp.host",this.mailServerHost);
p.put("mail.smtp.port",this.mailServerPort);
p.put("mail.smtp.auth",validate ? "true" :"false");
return p;
}
public String getMailServerHost(){
returnmailServerHost;
}
publicvoid setMailServerHost(String mailServerHost){
this.mailServerHost = mailServerHost;
}
publicStringgetMailServerPort() {
returnmailServerPort;
}
publicvoid setMailServerPort(String mailServerPort){
this.mailServerPort = mailServerPort;
}
publicboolean isValidate() {
returnvalidate;
}
publicvoid setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames(){
returnattachFileNames;
}
publicvoid setAttachFileNames(String[] fileNames){
this.attachFileNames = fileNames;
}
public String getFromAddress() {
returnfromAddress;
}
publicvoid setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
returnpassword;
}
publicvoid setPassword(String password) {
this.password = password;
}
public String getToAddress() {
returntoAddress;
}
publicvoid setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() { &nbs
补充:软件开发 , Java ,