本文主要是介绍JavaMail 发送邮件系列(一):发送基本邮件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用JavaMail API发送邮件,大概分为三个类:MyAuthenticator---密码认证器,MailSendInfo--邮件发送消息集合,MailSendUtils--邮件发送消息注入执行
Maven依赖
<dependency ><groupId > javax.mail </ groupId ><artifactId > mail </ artifactId ><version > 1.4.5 </ version >
</dependency >
<dependency ><groupId > com.sun.mail </ groupId ><artifactId > javax.mail </ artifactId ><version > 1.5.4 </ version >
</dependency >
MyAuthenticator
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;public class MyAuthenticator extends Authenticator {private String userName = null;private 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);}
}
MailSendInfo
import java.util.Properties;public class MailSenderInfo {// 发送邮件的服务器的IP和端口private String mailServerHost;private String mailServerPort = "25";// 邮件发送者的地址private String fromAddress;// 登陆邮件发送服务器的用户名和密码private String userName;private String password;// 是否需要身份验证private boolean validate = false;// 邮件主题private String subject;// 邮件的文本内容private String content;// 邮件接收者的地址private String[] toAddress;/*** 获得邮件会话属性*/public Properties getProperties() {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[] getToAddress() {return toAddress;}public void setToAddress(String[] toAddress) {this.toAddress = toAddress;}public String getMailServerHost() {return mailServerHost;}public void setMailServerHost(String mailServerHost) {this.mailServerHost = mailServerHost;}public String getMailServerPort() {return mailServerPort;}public void setMailServerPort(String mailServerPort) {this.mailServerPort = mailServerPort;}public boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}public String getFromAddress() {return fromAddress;}public void setFromAddress(String fromAddress) {this.fromAddress = fromAddress;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String textContent) {this.content = textContent;}
}
MailSendUtils
import java.util.Date;
import java.util.Properties;import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;public class MailSendUtils {private MailSenderInfo mailInfo = new MailSenderInfo();public MailSendUtils(String subject, String message,String toAddress) {mailInfo.setMailServerHost("smtp.163.com");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUserName("lweemooaiz.4r@163.com");mailInfo.setPassword("willsmith228");mailInfo.setFromAddress("lweemooaiz.4r@163.com");mailInfo.setToAddress(new String[]{toAddress});mailInfo.setSubject(subject);mailInfo.setContent(message);}/*** 以TEXT格式发送邮件* */public boolean sendTextMail() {// 判断是否需要身份认证MyAuthenticator authenticator = null;Properties pro = mailInfo.getProperties();if (mailInfo.isValidate()) {// 如果需要身份认证,则创建一个密码验证器authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession sendMailSession = Session.getDefaultInstance(pro, authenticator);try {// 根据session创建一个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中String[] ToAddresses = mailInfo.getToAddress();Address[] addressList = new InternetAddress[ToAddresses.length];for (int i = 0; i < ToAddresses.length; i++) {addressList[i] = new InternetAddress(ToAddresses[i]);}// Message.RecipientType.TO属性表示接收者的类型为TOmailMessage.setRecipients(Message.RecipientType.TO, addressList);// 设置邮件消息的主题mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// 设置邮件消息的主要内容String mailContent = mailInfo.getContent();mailMessage.setText(mailContent);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}/*** 以HTML格式发送邮件* */public boolean sendHtmlMail() {// 判断是否需要身份认证MyAuthenticator authenticator = null;Properties pro = mailInfo.getProperties();// 如果需要身份认证,则创建一个密码验证器if (mailInfo.isValidate()) {authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession sendMailSession = Session.getDefaultInstance(pro, authenticator);try {// 根据session创建一个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中String[] ToAddresses = mailInfo.getToAddress();Address[] addressList = new InternetAddress[ToAddresses.length];for (int i = 0; i < ToAddresses.length; i++) {addressList[i] = new InternetAddress(ToAddresses[i]);}// Message.RecipientType.TO属性表示接收者的类型为TOmailMessage.setRecipients(Message.RecipientType.TO, addressList);// 设置邮件消息的主题mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象Multipart mainPart = new MimeMultipart();// 创建一个包含HTML内容的MimeBodyPartBodyPart html = new MimeBodyPart();// 设置HTML内容html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");mainPart.addBodyPart(html);// 将MiniMultipart对象设置为邮件内容mailMessage.setContent(mainPart);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}
}
MailTest
public class MailTest {public static void main(String[] args) {MailSendUtils sms = new MailSendUtils("this is title", "this is content", "1813110015@qq.com");System.out.println(sms.sendTextMail());}}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.cnooc.commons</groupId><artifactId>CPURecordMonitor</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>CPURecordMonitor</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.7</version><scope>test</scope></dependency><dependency ><groupId >javax.mail </groupId ><artifactId >mail </artifactId ><version >1.4.5 </version ></dependency ><dependency ><groupId >com.sun.mail </groupId ><artifactId >javax.mail </artifactId ><version >1.5.4 </version ></dependency ></dependencies ><build ><finalName >CPURecordMonitor </finalName ><plugins ><plugin ><groupId >org.apache.maven.plugins </groupId ><artifactId >maven-compiler-plugin</artifactId ><configuration ><source >1.7 </source ><target >1.7 </target ></configuration ></plugin ></plugins ></build ></project>
中途遇到两个错误
java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
java.lang.NoClassDefFoundError: javax/mail/MessagingException
http://blog.csdn.net/u013361445/article/details/49663329
Demon下载:http://download.csdn.net/detail/u013361445/9246365
建议下载完毕后自己敲一遍代码,有助于理解。
这篇关于JavaMail 发送邮件系列(一):发送基本邮件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!