java郵件發送
『壹』 怎樣用java實現郵件的發送
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.rmi.UnknownHostException;
import java.util.StringTokenizer;
import sun.misc.BASE64Encoder;
public class Sender {
//private boolean debug = true;
BASE64Encoder encode=new BASE64Encoder();//用於加密後發送用戶名和密碼
static int dk=25;
private Socket socket;
public Sender(String server, int port) throws UnknownHostException,
IOException {
try {
socket = new Socket(server, dk);
} catch (SocketException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
//System.out.println("已經建立連接!");
}
}
// 注冊到郵件伺服器
public void helo(String server, BufferedReader in, BufferedWriter out)
throws IOException {
int result;
result = getResult(in);
// 連接上郵件服務後,伺服器給出220應答
if (result != 220) {
throw new IOException("連接伺服器失敗");
}
result = sendServer("HELO " + server, in, out);
// HELO命令成功後返回250
if (result != 250) {
throw new IOException("注冊郵件伺服器失敗!");
}
}
private int sendServer(String str, BufferedReader in, BufferedWriter out)
throws IOException {
out.write(str);
out.newLine();
out.flush();
/*
if (debug) {
System.out.println("已發送命令:" + str);
}
*/
return getResult(in);
}
public int getResult(BufferedReader in) {
String line = "";
try {
line = in.readLine();
/*
if (debug) {
System.out.println("伺服器返回狀態:" + line);
}
*/
} catch (Exception e) {
e.printStackTrace();
}
// 從伺服器返回消息中讀出狀態碼,將其轉換成整數返回
StringTokenizer st = new StringTokenizer(line, " ");
return Integer.parseInt(st.nextToken());
}
public void authLogin(MailMessage message, BufferedReader in,
BufferedWriter out) throws IOException {
int result;
result = sendServer("AUTH LOGIN", in, out);
if (result != 334) {
throw new IOException("用戶驗證失敗!");
}
result=sendServer(encode.encode(message.getUser().getBytes()),in,out);
//System.out.println("用戶名: "+encode.encode(message.getUser().getBytes()));
if (result != 334) {
throw new IOException("用戶名錯誤!");
}
result=sendServer(encode.encode(message.getPassword().getBytes()),in,out);
//result=sendServer(message.getPassword(),in,out);
//System.out.println("密碼: "+encode.encode(message.getPassword().getBytes()));
if (result != 235) {
throw new IOException("驗證失敗!");
}
}
// 開始發送消息,郵件源地址
public void mailfrom(String source, BufferedReader in, BufferedWriter out)
throws IOException {
int result;
result = sendServer("MAIL FROM:<" + source + ">", in, out);
if (result != 250) {
throw new IOException("指定源地址錯誤");
}
}
// 設置郵件收件人
public void rcpt(String touchman, BufferedReader in, BufferedWriter out)
throws IOException {
int result;
result = sendServer("RCPT TO:<" + touchman + ">", in, out);
if (result != 250) {
throw new IOException("指定目的地址錯誤!");
}
}
// 郵件體
public void data(String from, String to, String subject, String content,
BufferedReader in, BufferedWriter out) throws IOException {
int result;
result = sendServer("DATA", in, out);
// 輸入DATA回車後,若收到354應答後,繼續輸入郵件內容
if (result != 354) {
throw new IOException("不能發送數據");
}
out.write("From: " + from);
out.newLine();
out.write("To: " + to);
out.newLine();
out.write("Subject: " + subject);
out.newLine();
out.newLine();
out.write(content);
out.newLine();
// 句號加回車結束郵件內容輸入
result = sendServer(".", in, out);
//System.out.println(result);
if (result != 250) {
throw new IOException("發送數據錯誤");
}
}
// 退出
public void quit(BufferedReader in, BufferedWriter out) throws IOException {
int result;
result = sendServer("QUIT", in, out);
if (result != 221) {
throw new IOException("未能正確退出");
}
}
// 發送郵件主程序
public boolean sendMail(MailMessage message, String server) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
helo(server, in, out);// HELO命令
authLogin(message, in, out);// AUTH LOGIN命令
mailfrom(message.getFrom(), in, out);// MAIL FROM
rcpt(message.getTo(), in, out);// RCPT
data(message.getDatafrom(), message.getDatato(),
message.getSubject(), message.getContent(), in, out);// DATA
quit(in, out);// QUIT
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
再寫一個MailMessage.java,set/get方法即可。
『貳』 Java發郵件的幾種方式
下面給你介紹3種發送郵件的方式:
1:使用JavaMail發送郵件
『叄』 如何在 java 發郵件中提供鏈接
這是一個通過Java發送Email的例子,很多新手問道如何用JAVA發郵件,其實挺簡單的,Java給我們提供有此方面的類庫可以使用,以下就是一個例子:
view source
print?
001
import java.awt.*;
002
import java.awt.event.*;
003
import java.util.*;
004
import java.net.*;
005
import java.io.*;
006
import javax.swing.*;
007
public class MailTest {
008
public static
void main(String[]
args) {
009
JFrame frame = new
MailTestFrame();
010
frame.show();
011
}
012
}
013
class MailTestFrame extends JFrame implements ActionListener {
014
private BufferedReader in;
015
private PrintWriter out;
016
private JTextField from;
017
private JTextField to;
018
private JTextField
smtpServer;
019
private JTextArea message;
020
private JTextArea response;
021
022
public MailTestFrame() {
023
setTitle("MailTest");
024
setSize(300, 300);
025
addWindowListener(new WindowAdapter() {
026
public void windowClosing(WindowEvent e) {
027
System.exit(0);
028
}
029
});
030
getContentPane().setLayout(new GridBagLayout());
031
GridBagConstraints gbc = new GridBagConstraints();
032
// 當容器比組件要大時,只調整垂直方向組件的大小
033
gbc.fill = GridBagConstraints.HORIZONTAL;
034
gbc.weightx = 0;
035
gbc.weighty = 0;
036
037
gbc.weightx = 0;
038
add(new JLabel("發送地址:"), gbc, 0, 0, 1, 1);
039
gbc.weightx = 100;
040
from = new JTextField(20);
041
add(from, gbc, 1, 0, 1, 1);
042
gbc.weightx = 0;
043
add(new JLabel("收件地址:"), gbc, 0, 1, 1, 1);
044
gbc.weightx = 100;
045
to
= new JTextField(20);
046
add(to, gbc, 1, 1, 1, 1);
047
gbc.weightx = 0;
048
add(new JLabel("SMTP伺服器:"), gbc,
0, 2, 1, 1);
049
gbc.weightx = 100;
050
smtpServer = new
JTextField(20);
051
add(smtpServer, gbc, 1, 2, 1, 1);
052
gbc.fill = GridBagConstraints.BOTH;
053
gbc.weighty = 100;
054
message = new JTextArea();
055
add(new JScrollPane(message), gbc, 0, 3, 2, 1);
056
response = new JTextArea();
057
add(new JScrollPane(response), gbc, 0, 4, 2, 1);
058
gbc.weighty = 0;
059
JButton sendButton = new JButton("發送");
060
sendButton.addActionListener(this);
061
JPanel buttonPanel = new JPanel();
062
buttonPanel.add(sendButton);
063
add(buttonPanel, gbc, 0, 5, 2, 1);
064
}
065
private void add(Component c, GridBagConstraints gbc, int x, int y, int w,
066
int h) {
067
gbc.gridx = x;
068
gbc.gridy = y;
069
gbc.gridwidth = w;
070
gbc.gridheight = h;
071
getContentPane().add(c, gbc);
072
}
073
public void actionPerformed(ActionEvent evt) {
074
// 非同步機制,使得當所有的awt事件發生後才進行以下工作
075
SwingUtilities.invokeLater(new Runnable() {
076
public void run() {
077
sendMail();
078
}
079
});
080
}
081
public void sendMail() {
082
try {
083
Socket s = new Socket(smtpServer.getText(), 25);
084
out = new PrintWriter(s.getOutputStream());
085
in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
086
String hostName = InetAddress.getLocalHost().getHostName();
087
send(null);
088
// 傳送本機域名
089
send("HELO " + hostName);
090
// 傳送發信者信箱名稱
091
send("MAIL FROM: "
+ from.getText());
092
// 傳送收信者信箱名稱
093
send("RCPT TO: "
+ to.getText());
094
// 發送信箱數據,包括信頭和信體
095
send("DATA");
096
out.println(message.getText());
097
// 發送結束標志
098
send(".");
099
s.close();
100
}
catch (IOException exception) {
101
response.append("Error:
" + exception);
102
}
103
}
104
public void send(String s) throws IOException {
105
if (s != null) {
106
response.append(s + "\n");
107
out.println(s);
108
out.flush();
109
}
110
String line;
111
if ((line = in.readLine())
!= null)
112
response.append(line + "\n");
113
}
114
}
轉載僅供參考,版權屬於原作者。祝你愉快,滿意請採納哦
『肆』 如何用java實現發送html格式的郵件
首先Java發送郵件需要用到JavaMail,先到Oracle官網上下載好最新版本的JavaMail(剛才看了一下,最新是1.5.3),把下載的這個jar文件放到classpath里(如果是Web項目,就放到WEB-INF/lib目錄下。
JavaMail主要支持發送純文本的和html格式的郵件。
發送html格式的郵件的一個常式如下:
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeUtility;
importjavax.mail.Session;
importjavax.mail.MessagingException;
importjavax.mail.Transport;
publicclassSendHtmlMail{
publicstaticvoidsendMessage(StringsmtpHost,
Stringfrom,Stringto,
Stringsubject,StringmessageText)
throwsMessagingException,java.io.UnsupportedEncodingException{
//Step1:Configurethemailsession
System.out.println("Configuringmailsessionfor:"+smtpHost);
java.util.Propertiesprops=newjava.util.Properties();
props.setProperty("mail.smtp.auth","true");//指定是否需要SMTP驗證
props.setProperty("mail.smtp.host",smtpHost);//指定SMTP伺服器
props.put("mail.transport.protocol","smtp");
SessionmailSession=Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台顯示debug信息
//Step2:Constructthemessage
System.out.println("Constructingmessage-from="+from+"to="+to);
InternetAddressfromAddress=newInternetAddress(from);
InternetAddresstoAddress=newInternetAddress(to);
MimeMessagetestMessage=newMimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO,toAddress);
testMessage.setSentDate(newjava.util.Date());
testMessage.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
testMessage.setContent(messageText,"text/html;charset=gb2312");
System.out.println("Messageconstructed");
//Step3:Nowsendthemessage
Transporttransport=mailSession.getTransport("smtp");
transport.connect(smtpHost,"webmaster","password");
transport.sendMessage(testMessage,testMessage.getAllRecipients());
transport.close();
System.out.println("Messagesent!");
}
publicstaticvoidmain(String[]args){
StringsmtpHost="localhost";
Stringfrom="[email protected]";
Stringto="[email protected]";
Stringsubject="html郵件測試";//subjectjavamail自動轉碼
StringBuffertheMessage=newStringBuffer();
theMessage.append("<h2><fontcolor=red>這倒霉孩子</font></h2>");
theMessage.append("<hr>");
theMessage.append("<i>年年失望年年望</i>");
try{
SendHtmlMail.sendMessage(smtpHost,from,to,subject,theMessage.toString());
}
catch(javax.mail.MessagingExceptionexc){
exc.printStackTrace();
}
catch(java.io.){
exc.printStackTrace();
}
}
}
JavaMail是封裝了很多郵件操作的,所以使用起來不很困難,建議你到JavaMail官網看一下API或下載Java Doc API文檔。
『伍』 javaMail如何能保證郵件發送成功
當javamail使用smtp服務發送郵件時,當你把郵件發送到smtp伺服器的時候,你只能得到已經發送到smtp的隊列中的狀態,但是郵件伺服器是否能發送成功,你是得不到的。就是說,你不能保證郵件發送一定成功。 這就取決於SMTP協議的內容傳輸了。
但是SMTP協議如果傳輸失敗,是會報錯的。SMTP由TCP提供的可靠的數據傳輸服務把郵件消息從發信人的郵件伺服器傳送到收信人的郵件伺服器。
所以我們可以認為當我們調用JavaMail發送郵件時,如果程序沒有報錯則表示郵件發送成功。
SMTP通常有兩種工作模式:發送SMTP和接收SMTP。
具體工作方式為:發送SMTP在接到用戶的郵件請求後,判斷此郵件是否為本地郵件,若是直接投送到用戶的郵箱,否則向dns查詢遠端郵件伺服器的 MX紀錄,並建立與遠端接收SMTP之間的一個雙向傳送通道,此後SMTP命令由發送SMTP發出,由接收SMTP接收,而應答則反方面傳送。一旦傳送通 道建立,SMTP發送者發送MAIL命令指明郵件發送者。如果SMTP接收者可以接收郵件則返回OK應答。SMTP發送者再發出RCPT命令確認郵件是否 接收到。如果SMTP接收者接收,則返回OK應答;如果不能接收到,則發出拒絕接收應答(但不中止整個郵件操作),雙方將如此重復多次。當接收者收到全部 郵件後會接收到特別的序列,如果接收者成功處理了郵件,則返回OK應答即可。
『陸』 怎麼用JAVA實現郵件發送
用java mail 庫
『柒』 Java發送郵件
本地要 有smtp伺服器,才可以測試 。。。。。。。。。。。。。~
~
~
~~~~~~~~~~~~~~~~~~~~~~~~
『捌』 java 代碼發郵件怎麼添加附件
實現java發送郵件的過程大體有以下幾步:
准備一個properties文件,該文件中存放SMTP伺服器地址等參數。
利用properties創建一個Session對象
利用Session創建Message對象,然後設置郵件主題和正文
利用Transport對象發送郵件
需要的jar有2個:activation.jar和mail.jar發送附件,需要用到Multipart對象。
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
{
privateMimeMessagemessage;
privateSessionsession;
privateTransporttransport;
privateStringmailHost="";
privateStringsender_username="";
privateStringsender_password="";
privatePropertiesproperties=newProperties();
/*
*初始化方法
*/
publicJavaMailWithAttachment(booleandebug){
InputStreamin=JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");
try{
properties.load(in);
this.mailHost=properties.getProperty("mail.smtp.host");
this.sender_username=properties.getProperty("mail.sender.username");
this.sender_password=properties.getProperty("mail.sender.password");
}catch(IOExceptione){
e.printStackTrace();
}
session=Session.getInstance(properties);
session.setDebug(debug);//開啟後有調試信息
message=newMimeMessage(session);
}
/**
*發送郵件
*
*@paramsubject
*郵件主題
*@paramsendHtml
*郵件內容
*@paramreceiveUser
*收件人地址
*@paramattachment
*附件
*/
publicvoiddoSendHtmlEmail(Stringsubject,StringsendHtml,StringreceiveUser,Fileattachment){
try{
//發件人
InternetAddressfrom=newInternetAddress(sender_username);
message.setFrom(from);
//收件人
InternetAddressto=newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO,to);
//郵件主題
message.setSubject(subject);
//向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
Multipartmultipart=newMimeMultipart();
//添加郵件正文
BodyPartcontentPart=newMimeBodyPart();
contentPart.setContent(sendHtml,"text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
//添加附件的內容
if(attachment!=null){
BodyPartattachmentBodyPart=newMimeBodyPart();
DataSourcesource=newFileDataSource(attachment);
attachmentBodyPart.setDataHandler(newDataHandler(source));
//網上流傳的解決文件名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定
//這里很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼
//sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?"+enc.encode(attachment.getName().getBytes())+"?=");
//MimeUtility.encodeWord可以避免文件名亂碼
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
//將multipart對象放到message中
message.setContent(multipart);
//保存郵件
message.saveChanges();
transport=session.getTransport("smtp");
//smtp驗證,就是你用來發郵件的郵箱用戶名密碼
transport.connect(mailHost,sender_username,sender_password);
//發送
transport.sendMessage(message,message.getAllRecipients());
System.out.println("sendsuccess!");
}catch(Exceptione){
e.printStackTrace();
}finally{
if(transport!=null){
try{
transport.close();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
}
publicstaticvoidmain(String[]args){
JavaMailWithAttachmentse=newJavaMailWithAttachment(true);
Fileaffix=newFile("c:\測試-test.txt");
se.doSendHtmlEmail("郵件主題","郵件內容","[email protected]",affix);//
}
}
『玖』 如何用java實現發郵件功能,並有幾點注意事項
packagecom.victor;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
{
privateMimeMessagemessage;
privateSessionsession;
privateTransporttransport;
privateStringmailHost="";
privateStringsender_username="";
privateStringsender_password="";
privatePropertiesproperties=newProperties();
/*
*初始化方法
*/
publicJavaMailWithAttachment(booleandebug){
InputStreamin=JavaMailWithAttachment.class.getResourceAsStream("/MailServer.properties");
try{
properties.load(in);
this.mailHost=properties.getProperty("mail.smtp.host");
this.sender_username=properties.getProperty("mail.sender.username");
this.sender_password=properties.getProperty("mail.sender.password");
}catch(IOExceptione){
e.printStackTrace();
}
session=Session.getInstance(properties);
session.setDebug(debug);//開啟後有調試信息
message=newMimeMessage(session);
}
/**
*發送郵件
*
*@paramsubject
*郵件主題
*@paramsendHtml
*郵件內容
*@paramreceiveUser
*收件人地址
*@paramattachment
*附件
*/
publicvoiddoSendHtmlEmail(Stringsubject,StringsendHtml,StringreceiveUser,Fileattachment){
try{
//發件人
InternetAddressfrom=newInternetAddress(sender_username);
message.setFrom(from);
//收件人
InternetAddressto=newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO,to);
//郵件主題
message.setSubject(subject);
//向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
Multipartmultipart=newMimeMultipart();
//添加郵件正文
BodyPartcontentPart=newMimeBodyPart();
contentPart.setContent(sendHtml,"text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
//添加附件的內容
if(attachment!=null){
BodyPartattachmentBodyPart=newMimeBodyPart();
DataSourcesource=newFileDataSource(attachment);
attachmentBodyPart.setDataHandler(newDataHandler(source));
//網上流傳的解決文件名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定
//這里很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼
//sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?"+enc.encode(attachment.getName().getBytes())+"?=");
//MimeUtility.encodeWord可以避免文件名亂碼
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
//將multipart對象放到message中
message.setContent(multipart);
//保存郵件
message.saveChanges();
transport=session.getTransport("smtp");
//smtp驗證,就是你用來發郵件的郵箱用戶名密碼
transport.connect(mailHost,sender_username,sender_password);
//發送
transport.sendMessage(message,message.getAllRecipients());
System.out.println("sendsuccess!");
}catch(Exceptione){
e.printStackTrace();
}finally{
if(transport!=null){
try{
transport.close();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
}
publicstaticvoidmain(String[]args){
JavaMailWithAttachmentse=newJavaMailWithAttachment(true);
System.out.println(se);
Fileaffix=newFile("E:\測試-test.txt");
//Fileaffix=null;
se.doSendHtmlEmail("##","###","####@##.com",affix);//
}
}
注意點:1 jar可能有沖突,如果是demo可以直接應用mail.jar
如果是一個工程則要替換javaEE中的mail.jar包
2 關於properties配置文件的地址問題
Class.getResourceAsStream(String path) : path 不以』/'開頭時默認是從此類所在的包下取資源,以』/'開頭則是從
ClassPath根下獲取。其只是通過path構造一個絕對路徑,最終還是由ClassLoader獲取資源。