java郵件實例_java郵件小實例

新建一個包,名為mail

第一個類:MailSenderInfo.java

###########################################

package com.util.mail;

/**

* 發送郵件需要使用的基本信息

*author by wangfun

http://www.5a520.cn 小說520

*/

import java.util.Properties;

public class MailSenderInfo {

// 發送郵件的服務器的IP和端口

private String mailServerHost;

private String mailServerPort = "25";

// 郵件發送者的地址

private String fromAddress;

// 郵件接收者的地址

private String toAddress;

// 登陸郵件發送服務器的用戶名和密碼

private String userName;

private String password;

// 是否需要身份驗證

private boolean validate = false;

// 郵件主題

private String subject;

// 郵件的文本內容

private String content;

// 郵件附件的文件名

private String[] attachFileNames;

/**

* 獲得郵件會話屬性

*/

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 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[] getAttachFileNames() {

return attachFileNames;

}

public void setAttachFileNames(String[] fileNames) {

this.attachFileNames = fileNames;

}

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 getToAddress() {

return toAddress;

}

public void setToAddress(String toAddress) {

this.toAddress = toAddress;

}

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;

}

}

#########################################################

第二個類:SimpleMailSender.java

#############################################################

package com.util.mail;

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;

/**

* 簡單郵件(不帶附件的郵件)發送器

http://www.bt285.cn BT下載

*/

public class SimpleMailSender ?{

/**

* 以文本格式發送郵件

* @param mailInfo 待發送的郵件的信息

*/

public boolean sendTextMail(MailSenderInfo mailInfo) {

// 判斷是否需要身份認證

MyAuthenticator authenticator = null;

Properties pro = mailInfo.getProperties();

if (mailInfo.isValidate()) {

// 如果需要身份認證,則創建一個密碼驗證器

authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

}

// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session

Session sendMailSession = Session.getDefaultInstance(pro,authenticator);

try {

// 根據session創建一個郵件消息

Message mailMessage = new MimeMessage(sendMailSession);

// 創建郵件發送者地址

Address from = new InternetAddress(mailInfo.getFromAddress());

// 設置郵件消息的發送者

mailMessage.setFrom(from);

// 創建郵件的接收者地址,并設置到郵件消息中

Address to = new InternetAddress(mailInfo.getToAddress());

mailMessage.setRecipient(Message.RecipientType.TO,to);

// 設置郵件消息的主題

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格式發送郵件

* @param mailInfo 待發送的郵件信息

*/

public static boolean sendHtmlMail(MailSenderInfo mailInfo){

// 判斷是否需要身份認證

MyAuthenticator authenticator = null;

Properties pro = mailInfo.getProperties();

//如果需要身份認證,則創建一個密碼驗證器

if (mailInfo.isValidate()) {

authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());

}

// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session

Session sendMailSession = Session.getDefaultInstance(pro,authenticator);

try {

// 根據session創建一個郵件消息

Message mailMessage = new MimeMessage(sendMailSession);

// 創建郵件發送者地址

Address from = new InternetAddress(mailInfo.getFromAddress());

// 設置郵件消息的發送者

mailMessage.setFrom(from);

// 創建郵件的接收者地址,并設置到郵件消息中

Address to = new InternetAddress(mailInfo.getToAddress());

// Message.RecipientType.TO屬性表示接收者的類型為TO

mailMessage.setRecipient(Message.RecipientType.TO,to);

// 設置郵件消息的主題

mailMessage.setSubject(mailInfo.getSubject());

// 設置郵件消息發送的時間

mailMessage.setSentDate(new Date());

// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象

Multipart mainPart = new MimeMultipart();

// 創建一個包含HTML內容的MimeBodyPart

BodyPart 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;

}

}

#######################################################

第三個類:MyAuthenticator.java

########################################################

package com.util.mail;

import javax.mail.*;

public class MyAuthenticator 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);

}

}

############################################################

下面給出使用上面三個類的代碼:

############################################################

public static void main(String[] args){

//這個類主要是設置郵件

MailSenderInfo mailInfo = new MailSenderInfo();

mailInfo.setMailServerHost("smtp.163.com");

mailInfo.setMailServerPort("25");

mailInfo.setValidate(true);

mailInfo.setUserName("han2000lei@163.com");

mailInfo.setPassword("**********");//您的郵箱密碼

mailInfo.setFromAddress("han2000lei@163.com");

mailInfo.setToAddress("han2000lei@163.com");

mailInfo.setSubject("設置郵箱標題 如http://www.guihua.org 中國桂花網");

mailInfo.setContent("設置郵箱內容 如http://www.guihua.org 中國桂花網 是中國最大桂花網站==");

//這個類主要來發送郵件

SimpleMailSender sms = new SimpleMailSender();

sms.sendTextMail(mailInfo);//發送文體格式

sms.sendHtmlMail(mailInfo);//發送html格式

}

##################################################################

最后,給出朋友們幾個注意的地方:

1、使用此代碼你可以完成你的javamail的郵件發送功能。三個類缺一不可。

2、這三個類我打包是用的com.util.mail包,如果不喜歡,你可以自己改,但三個類文件必須在同一個包中

3、不要使用你剛剛注冊過的郵箱在程序中發郵件,如果你的163郵箱是剛注冊不久,那你就不要使用“smtp.163.com”。因為你發不出去。剛注冊的郵箱是不會給你這種權限的,也就是你不能通過驗證。要使用你經常用的郵箱,而且時間比較長的。

4、另一個問題就是mailInfo.setMailServerHost("smtp.163.com");與mailInfo.setFromAddress("han2000lei@163.com");這兩句話。即如果你使用163smtp服務器,那么發送郵件地址就必須用163的郵箱,如果不的話,是不會發送成功的。

5、關于javamail驗證錯誤的問題,網上的解釋有很多,但我看見的只有一個。就是我的第三個類。你只要復制全了代碼,我想是不會有問題的。

Eclipse下如何導入jar包:http://blog.csdn.net/justinavril/article/details/2783182

1.右擊工程的根目錄,點擊屬性進入屬性。

2.在屬性頁面中選中Java Build Path,選中 庫 標簽,點擊Add External JARs。

3.找到需要添加的jar包,確定即可。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/397613.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/397613.shtml
英文地址,請注明出處:http://en.pswp.cn/news/397613.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

DEV GridView嵌套

/// <summary> /// 綁定主表和明顯表到GridView /// </summary> /// <param name"machineProduct">主表</param> /// <param name"configureData">字表</param> private void Mas…

局域網大型文件分發的可能解決方案

客戶原來的做法是把文件上傳到服務器&#xff0c;然后后形成一個普通的HTTP地址下入網站后臺系統&#xff0c;然后客戶端用戶看到后&#xff0c;則下載下來。但是隨著文件越來越大&#xff0c;客戶端下載量增加&#xff0c;在局域內網環境中這種文件分發方式的弊端立現。服務器…

android——獲取ImageView上面顯示的圖片bitmap對象

獲取的函數方法為&#xff1a;Bitmap bitmapimageView.getDrawingCache(); 但是如果只是這樣寫我們得到的bitmap對象可能為null值&#xff0c;正確的方式為&#xff1a; imageView.setDrawingCacheEnabled(true);Bitmap bitmapimageView.getDrawingCache();imageView.setDrawin…

java監聽com口_簡單了解Java接口+事件監聽機制

1.接口&#xff1a;定義方法&#xff1a;public interface interName //extends interName2, interName3...可繼承多個接口在接口里只能定義常量和抽象方法。public static final String Name;public abstract void method(String Name);//這里不能用大括號&#xff0c;不然就不…

例子:好友列表選中效果

<style type"text/css"> *{ margin:0px auto; padding:0px; font-family:微軟雅黑; font-size:16px;} .f{ width:200px; height:30px; background-color:#63C; color:white; text-align:center; line-height:30px; vertical-align:middle; margin-top:3px} .f:…

sublime 常用插件

AutoFileName 文件提示路徑&#xff0c;在img,script的[src]屬性。link,a的[href]屬性&#xff0c;background 的[url]屬性后提示文件的路徑 CSS Format css格式化工具 Pretty JSON json格式化工具轉載于:https://www.cnblogs.com/zhangtao1990/p/9231608.html

有一句說一千句,是作家....

有一句說一千句&#xff0c;是作家&#xff0c;這叫文采&#xff1b;有一句說一百句&#xff0c;是演說家&#xff0c;這叫口才&#xff1b;有一句說十句&#xff0c;是教授&#xff0c;這叫學問&#xff1b;有一句說一句&#xff0c;是律師&#xff0c;這叫嚴謹&#xff1b;說…

java jsoup爬取動態網頁_java通過Jsoup爬取網頁(入門教程)

一&#xff0c;導入依賴org.jsoupjsoup1.10.3org.apache.httpcomponentshttpclient二&#xff0c;編寫demo類注意不要導錯包了,是org.jsoup.nodes下面的package com.taotao.entity;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResp…

Java設計模式之七大結構型模式

總體來說設計模式分為三大類&#xff1a;創建型模式、結構型模式和行為型模式。 結構型模式&#xff0c;共有七種&#xff1a;適配器模式、裝飾器模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。 其中適配器模式主要分為三類&#xff1a;類的適配器模式、對象的適配…

一個Option請求引發的深度解析

在當前項目中&#xff0c;前端通過POST方式訪問后端的REST接口時&#xff0c;發現兩條請求記錄&#xff0c;一條請求的Request Method為Options&#xff0c;另一條請求的Reuest Method為Post。想要解決這個疑惑還得從以下3個概念說起。 Http Options Method RFC2616標準&#x…

ionic+AnjularJs實現省市縣三級聯動效果

建議對ionic和AnjularJs有一定了解的人可以用到&#xff0c;很多時候我們要用到選擇省份、城市、區縣的功能&#xff0c;現在就跟著我來實現這個功能吧&#xff0c;用很少的代碼&#xff08;我這里是根據客戶的要求&#xff0c;只顯示想要顯示的部分省份和其相對應的城市、區縣…

md5和SHA校驗碼

md5已經不安全了,中國山東大學女學霸王小云破解了一系列密碼,當真是巾幗不讓須眉.說是破解,其實就是給你一個md5碼,讓你求出這個md5碼所對應的原始信息,顯然一個md5對應無數種原始信息.而md5的特性就是難以還原初始信息,但是王小云可以迅速找到給定md5碼的可行解.md5的解空間雖…

Confluence 6 附件存儲文件系統的分級

從 Confluence 3.0 開始&#xff0c;附件的存儲方式有了重大的改變和升級。如果你是從 Confluence 2.10 及其早期版本升級上來的&#xff0c;請參考 Upgrading Confluence 頁面中推薦的升級路徑&#xff0c;同時請閱讀 Confluence 3.0 文檔中 Hierarchical File System Attachm…

Fragment與Activity交互(使用接口)

在Fragment中: 1. // 定義一個回調接口&#xff0c;該Fragment所在Activity需要實現該接口// 該Fragment將通過該接口與它所在的Activity交互 { public void onItemSelected(Integer id);}2. // 當該Fragment被添加、顯示到Activity時&#xff0c;回調該方法 public void onA…

java保齡球計分_自己寫的java保齡球記分

package com.java.bowlingscore1;import java.util.Arrays;public class Game { int[] bowlingScore new int[21]; //用來存放投擲擊倒的數目 int ball0; //數組下標 int score;//分數 int countframe0;//記錄當前是第幾輪 boolean firs…

你不知道的JavaScript-0

【數組】 刪除數組的幾種方法&#xff1a; https://www.cnblogs.com/Joans/p/3981122.html http://www.cnblogs.com/qiantuwuliang/archive/2010/09/01/1814706.html 【數字轉換】 parseInt(num, radix): 【寬松相等和嚴格相等】 允許在相等比較中進行強制類型轉換&#xff0c…

真是,原來可以這樣啊

一下午&#xff0c;解決了兩個問題。。。。。 先列上這兩個真是Bug的問題&#xff1a; 1、數據庫有個表book&#xff0c;里面有個字段 create_time Datetime類型的字段&#xff0c;這個字段是 not null 的。下午下代碼往數據庫里插入數據時&#xff0c;總是提示&#xff0c;cre…

1026. Table Tennis (30)

題目如下&#xff1a; A table tennis club has N tables available to the public. The tables are numbered from 1 to N. For any pair of players, if there are some tables open when they arrive, they will be assigned to the available table with the smallest numb…

java運行時異常中文_JAVA——運行時異常(RuntimeException)

Exception中有一個特殊的子類異常RuntimeException運行時異常。如果在函數內拋出該異常&#xff0c;函數上可以不用聲明&#xff0c;編譯一樣通過。如果在函數上聲明了該異常。調用者可以不用進行處理。編譯一樣通過。之所以不用在函數上聲明&#xff0c;是因為不需要讓調用者處…

內置函數isinstance和issubclass

1. isinstance&#xff08;obj,class&#xff09; 判斷對象obj是不是由class生成的對象。 class Foo:passobjFoo()print(isinstance(obj,Foo))obj是Foo的生成的對象&#xff0c;返回True。如果不是&#xff0c;則返回False。 d{x:1} #ddict({x:1} #)print(type(d) is dict) pri…