本文目錄一覽:
怎麼用JAVA實現郵件發送
一個小例子,也可使用其他api
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
import javax.mail.internet.MimeUtility;
public class Test {
// test
public static void main(String[] args) throws Exception {
sendEmail(“smtp.163.com”, “測試”, “測試”, “!!!收件人地址!!!”, “!!!發件人郵箱用戶名!!!”, “!!!郵箱密碼!!!”, “發件人昵稱”);
}
/**
*
* @param smtp
* @throws Exception
*/
public static void sendEmail(String emailServer, String subject, String mailBody, String receiver, final String username, final String password, String nickname) throws Exception {
Properties props = new Properties();
props.put(“mail.smtp.auth”, “true”);
props.setProperty(“mail.transport.protocol”, “smtp”);
props.setProperty(“mail.smtp.host”, emailServer);
props.setProperty(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.setProperty(“mail.smtp.socketFactory.fallback”, “false”);
props.setProperty(“mail.smtp.port”, “465”);
props.setProperty(“mail.smtp.socketFactory.port”, “465”);
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
MimeMessage mimeMsg = new MimeMessage(session);
Multipart mp = new MimeMultipart();
mimeMsg.setSubject(MimeUtility.encodeText(subject, “utf-8”, null));
nickname = MimeUtility.encodeText(nickname, “utf-8”, null);
mimeMsg.setFrom(new InternetAddress(username, nickname, “UTF-8”));
BodyPart bp = new MimeBodyPart();
bp.setContent(mailBody, “text/html;charset=utf-8”);
mp.addBodyPart(bp);
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
Transport transport = session.getTransport();
transport.connect(username, password);
Address[] allRecipients = mimeMsg.getAllRecipients();
transport.sendMessage(mimeMsg, allRecipients);
transport.close();
}
}
怎樣用java發送郵件
首先下載 JavaMail jar 包,並導入到項目中。下載地址
編寫代碼,代碼如下:
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class App45 {
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = System.getProperties();
properties.setProperty(“mail.smtp.host”, “郵件發送服務器”);
properties.setProperty(“mail.smtp.auth”, “true”);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 設置發件人郵件帳號和密碼
return new PasswordAuthentication(“郵件帳號”, “密碼”);
}
});
MimeMessage message = new MimeMessage(session);
// 設置發件人郵件地址
message.setFrom(new InternetAddress(“發件人郵件地址”));
// 設置收件人郵件地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(“收件人郵件地址”));
message.setSubject(“這裡是郵件主題。”);
message.setText(“這裡是郵件內容。”);
Transport.send(message);
}
}
java 怎麼實現發送郵件例子
第一個類:MailSenderInfo.java
[java] view plain copy
package com.util.mail;
/**
* 發送郵件需要使用的基本信息
*author by wangfun
小說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
[java] view plain copy
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;
/**
* 簡單郵件(不帶附件的郵件)發送器
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
[java] view plain copy
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);
}
}
下面給出使用上面三個類的代碼:
[java] view plain copy
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(“設置郵箱標題 如 中國桂花網”);
mailInfo.setContent(“設置郵箱內容 如 中國桂花網 是中國最大桂花網站==”);
//這個類主要來發送郵件
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驗證錯誤的問題,網上的解釋有很多,但我看見的只有一個。就是我的第三個類。你只要複製全了代碼,我想是不會有問題的。
如何使用Java發送qq郵件
方法:
1.前提準備工作:
首先,郵件的發送方要開啟POP3 和SMTP服務–即發送qq郵件的賬號要開啟POP3 和SMTP服務
2.開啟方法:
登陸qq郵箱
3.點擊 設置
4.點擊—-賬戶
5.找到:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務 —點擊開啟
6.送短信 —–點擊確定
7.稍等一會,很得到一個授權碼! –注意:這個一定要記住,一會用到
8.點擊保存修改 —OK 完成
9.java 測試代碼:
package cn.cupcat.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class SendmailUtil {
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.put(“mail.transport.protocol”, “smtp”);// 連接協議
properties.put(“mail.smtp.host”, “smtp.qq.com”);// 主機名
properties.put(“mail.smtp.port”, 465);// 端口號
properties.put(“mail.smtp.auth”, “true”);
properties.put(“mail.smtp.ssl.enable”, “true”);//設置是否使用ssl安全連接 —一般都使用
properties.put(“mail.debug”, “true”);//設置是否顯示debug信息 true 會在控制台顯示相關信息
//得到回話對象
Session session = Session.getInstance(properties);
// 獲取郵件對象
Message message = new MimeMessage(session);
//設置發件人郵箱地址
message.setFrom(new InternetAddress(“123456789@qq.com”));
//設置收件人地址 message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress(“987654321@qq.com”) });
//設置郵件標題
message.setSubject(“這是第一封Java郵件”);
//設置郵件內容
message.setText(“內容為: 這是第一封java發送來的郵件。”);
//得到郵差對象
Transport transport = session.getTransport();
//連接自己的郵箱賬戶
transport.connect(“123456789@qq.com”, “vvctybgbvvophjcj”);//密碼為剛才得到的授權碼
//發送郵件 transport.sendMessage(message, message.getAllRecipients());
}
}
10.運行就會發出郵件了。。。。
下面是我收到郵件的截圖,當然我把源碼中的郵件地址都是修改了,不是真實的,你們測試的時候,可以修改能你們自己的郵箱。最後,祝你也能成功,如果有什麼問題,可以一起討論!
注意事項
得到的授權碼一定要保存好,程序中要使用
Java收發郵件過程中具體的功能是怎麼實現的
1.SMTP協議
用戶連上郵件服務器後,要想給它發送一封電子郵件,需要遵循一定的通迅規則,SMTP協議就是用於定義這種通訊規則的。
因而,通常我們也把處理用戶smtp請求(郵件發送請求)的郵件服務器稱之為SMTP服務器。(25)
2.POP3協議
同樣,用戶若想從郵件服務器管理的電子郵箱中接收一封電子郵件的話,他連上郵件服務器後,也需要遵循一定的通迅格式,POP3協議用於定義這種通訊格式。
因而,通常我們也把處理用戶pop3請求(郵件接收請求)的郵件服務器稱之為POP3服務器。(110)
下圖用於演示兩帳戶相互發送郵件的過程
3.1JavaMail API按其功能劃分通常可分為如下三大類:
創建和解析郵件內容的API :Message類是創建和解析郵件的核心API,它的實例對象代表一封電子郵件。
3.2發送郵件的API:Transport類是發送郵件的核心API類,它的實例對象代表實現了某個郵件發送協議的郵件發送對象,例如SMTP協議。
接收郵件的API:Store類是接收郵件的核心API類,它的實例對象代表實現了某個郵件接收協議的郵件接收對象,例如POP3協議。
3.3Session類
Session類用於定義整個應用程序所需的環境信息,以及收集客戶端與郵件服務器建立網絡連接的會話信息,如郵件服務器的主機名、端口號、採用的郵件發送和接收協議等。Session對象根據這些信息構建用於郵件收發的Transport和Store對象,以及為客戶端創建Message對象時提供信息支持。
4.郵件組織結構相關的API
MimeMessage類表示整封郵件。
MimeBodyPart類表示郵件的一個MIME消息。
MimeMultipart類表示一個由多個MIME消息組合成的組合MIME消息。
5.具體的例子程序
package cn.edu.dlmu.send;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
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;
import javax.mail.internet.MimeUtility;
public class SendMail {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
//連接的郵件服務器的主機名
prop.setProperty(“mail.smtp.host”, “smtp.sina.com.cn”);
//發送郵件的協議
prop.setProperty(“mail.transport.protocol”, “smtp”);
//是否向郵件服務器提交認證
prop.setProperty(“mail.smtp.auth”, “true”);
//創建session
Session session = Session.getInstance(prop);
session.setDebug(true);
//得到transport
Transport ts = session.getTransport();
//連接郵件服務器
ts.connect(“smtp.sina.com.cn”, “xxxx@sina.com”, “xxxxx”);
//發送郵件
MimeMessage message = createMessage(session);
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
public static MimeMessage createMessage(Session session) throws Exception {
MimeMessage message = new MimeMessage(session);
//設置郵件的基本信息
message.setFrom(new InternetAddress(“xxxx@sina.com”));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(“1219070362@qq.com”));
message.setSubject(“test”);
//正文
MimeBodyPart text = new MimeBodyPart();
//設置charaset可以解決中文正文的亂碼問題,內嵌可下載的圖片
text.setContent(“你好xxx,img src=’c:/dog.jpg’ /測試成功!br/img src=’cid:aaa.jpg’ /”, “text/html;charset=gbk”);
//圖片1
MimeBodyPart image = new MimeBodyPart();
image.setDataHandler(new DataHandler(new FileDataSource(“src/88.jpg”)));
image.setContentID(“aaa.jpg”);
//附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(“src/javamail架包.jar”));
attach.setDataHandler(dh);
//解決文件中文亂碼問題
attach.setFileName(MimeUtility.encodeText(dh.getName()));
//描述正文和圖片的關係
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(image);
mp.setSubType(“related”);
//描述正文和附件
MimeMultipart mp2 = new MimeMultipart();
mp2.addBodyPart(attach);
//將正文封裝為一個body
MimeBodyPart content = new MimeBodyPart();
content.setContent(mp);
mp2.addBodyPart(content);
mp2.setSubType(“mixed”);
message.setContent(mp2);
message.saveChanges();
return message;
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/243147.html