導航:首頁 > 編程語言 > java郵件

java郵件

發布時間:2022-02-06 18:10:29

java發郵件的幾種方式

下面給你介紹3種發送郵件的方式:

1:使用JavaMail發送郵件

㈡ Java發送郵件

本地要 有smtp伺服器,才可以測試 。。。。。。。。。。。。。~
~
~
~~~~~~~~~~~~~~~~~~~~~~~~

㈢ javamail如何判斷郵件狀態

pop3伺服器是不支持此做法的,
你用Foxmail收郵件(保留備份在伺服器上),然後再用郵件伺服器自帶的web收郵件,最後用OE收郵件,
我以前處理這一問題的做法供你參考參考:
收郵件時把郵件的唯一的UID字元串取出,並保存到web伺服器的一個文本文件中,
這樣就可以實現通過判斷pop3伺服器上的每一郵件的UID
是否已存在於文本文件中來確定是否為新郵件了.

㈣ 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實現郵件的發送

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方法即可。

㈥ javamail 回復郵件代碼

import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

/**
* <p>Title: java mail</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author petehero
* @version 1.0
*/

class SendMail
{
/**
* Logger for this class
*/

private static String server = "smtp.163.com";//smtp主機名。
private static String from = "[email protected]";//發送方郵件地址
private static String pw = "XXXXXX";//發送方郵件密碼。
private static String to = "[email protected]"; //接收方郵件地址
static String subject="hello";
/*BodyPart bp = new MimeBodyPart();
Multipart mp = new MimeMultipart();
DataSource source = new FileDataSource("a.jpg");//附件
*/

static String mailContent="你好!\n\n"+"\t郵件正文test\n\n";//郵件正文

public static void send()
{

try
{
Properties props = new Properties();
Session sendMailSession;
Store store;
Transport transport;
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host",server);
props.put("mail.smtp.user",from);
props.put("mail.smtp.password",pw);
//PopupAuthenticator popA=new PopupAuthenticator();
//PasswordAuthentication pop = popA.performCheck(from, pw);
//sendMailSession = Session.getInstance(props,popA);//填寫用戶名及密碼
sendMailSession = Session.getInstance(props,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication() //郵件安全認證。
{
return new PasswordAuthentication(from, pw);
}
});

Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(from));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
newMessage.setSubject(subject);
newMessage.setSentDate(new Date());
/*
bp.setText("bptext");
mp.addBodyPart(bp);
bp = new MimeBodyPart();
bp.setDataHandler(new DataHandler(source));
bp.setFileName("141.txt");
mp.addBodyPart(bp);
newMessage.setContent(mp);
*/
mailContent+=new Date().toLocaleString();
newMessage.setText(mailContent);
transport = sendMailSession.getTransport("smtp");
//System.out.println("Sending...");
//transport
Transport.send(newMessage);
//Transport.send(newMessage );
//System.out.println(server+from+pw+to);

}
catch (MessagingException ex)
{

}
}
// public static void main(String[] args)
// {
//
//// for(int i=0;i<args.length;i++)
//// {
//// System.out.println(args[i]);
//// }
//
// from=args[0].trim();
////
// pw=args[1].trim();
////
// SendMail sml = new SendMail();
// sml.send();
//// String a=SendMail.mailSend("hello","world");
//// System.out.println(a);
// }
static String mailSend(String t_to,String t_subject,String t_text)
{ String state="";
to=t_to;
subject=t_subject;

mailContent=t_text+"\n\n";
SendMail sml = new SendMail();
sml.send();
state="Successful";

return state;
}

/* public class PopupAuthenticator extends Authenticator{
String username=null;
String password=null;
public PopupAuthenticator(){}
public PasswordAuthentication performCheck(String user,String pass){
username = user;
password = pass;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}

}*/
}

㈦ javamail怎麼刪除指定郵件

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.AndTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;

/**
* 使用 java.mail.search 包中的 SearchTerm 類
* 在接收郵件時進行組合搜索、過濾
* @author haolloyin
*/
public class SearchMails {
public static void main(String[] args) throws Exception {
// 連接pop3伺服器的主機名、協議、用戶名、密碼
String pop3Server = "pop3.126.com";
String protocol = "pop3";
String user = "testhao";
String pwd = "123456";

// 創建一個有具體連接信息的Properties對象
Properties props = new Properties();
props.setProperty("mail.store.protocol", protocol);
props.setProperty("mail.pop3.host", pop3Server);

// 使用Properties對象獲得Session對象
Session session = Session.getInstance(props);
session.setDebug(true);

// 利用Session對象獲得Store對象,並連接pop3伺服器
Store store = session.getStore();
store.connect(pop3Server, user, pwd);

// 獲得郵箱內的郵件夾Folder對象,以"讀-寫"打開
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_WRITE);

// 搜索發件人為 [email protected] 和主題為"測試1"的郵件
SearchTerm st = new AndTerm(
new FromStringTerm("[email protected]"),
new SubjectTerm("測試1"));

// // 獲得郵件夾Folder內的所有郵件Message對象
// Message [] messages = folder.getMessages();

// 不是像上面那樣直接返回所有郵件,而是使用Folder.search()方法
Message [] messages = folder.search(st);
int mailCounts = messages.length;
System.out.println("搜索過濾到" + mailCounts + " 封符合條件的郵件!");

for(int i = 0; i < mailCounts; i++) {

String subject = messages[i].getSubject();
String from = (messages[i].getFrom()[0]).toString();

System.out.println("第 " + (i+1) + "封郵件的主題:" + subject);
System.out.println("第 " + (i+1) + "封郵件的發件人地址:" + from);

System.out.println("是否刪除該郵件(yes/no)?:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if("yes".equalsIgnoreCase(input)) {
// 直接輸出到控制台中
// messages[i].writeTo(System.out);
// 設置刪除標記,一定要記得調用saveChanges()方法
messages[i].setFlag(Flags.Flag.DELETED, true);
messages[i].saveChanges();
System.out.println("成功設置了刪除標記!");
}
}
// 關閉連接時設置了刪除標記的郵件才會被真正刪除,相當於"QUIT"命令
folder.close(false);
store.close();
}
}

㈧ java 發送郵件

要兩個java文件 還有一個mail.jar是不是只能用javamail誰也不敢說

第一個:

public class Constant {

public static final String mailAddress ="用戶名@163.com";
public static final String mailCount ="用戶名";
public static final String mailPassword ="密碼";
public static final String mailServer ="smtp.163.com";
//pukeyouxintest,

}

第二個:

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
/**
* 發送簡單郵件
* @param str_from:發件人地址
* @param str_to:收件人地址
* @param str_title:郵件標題
* @param str_content:郵件正文
*/
public static void send(String str_from,String str_to,String str_title,String str_content) {

// str_content="<a href='www.163.com'>html元素</a>"; //for testing send html mail!

try {
//建立郵件會話
Properties props=new Properties(); //用來在一個文件中存儲鍵-值對的,其中鍵和值是用等號分隔的,
//存儲發送郵件伺服器的信息
props.put("mail.smtp.host",Constant.mailServer);
//同時通過驗證
props.put("mail.smtp.auth","true");
//根據屬性新建一個郵件會話
Session s=Session.getInstance(props);
s.setDebug(true); //有他會列印一些調試信息。

//由郵件會話新建一個消息對象
MimeMessage message=new MimeMessage(s);

//設置郵件
InternetAddress from= new InternetAddress(str_from); //[email protected]
message.setFrom(from); //設置發件人的地址
//
// //設置收件人,並設置其接收類型為TO
InternetAddress to=new InternetAddress(str_to); //[email protected]
message.setRecipient(Message.RecipientType.TO, to);

//設置標題
message.setSubject(str_title); //java學習

//設置信件內容
// message.setText(str_content); //發送文本郵件 //你好嗎?
message.setContent(str_content, "text/html;charset=gbk"); //發送HTML郵件 //<b>你好</b><br><p>大家好</p>
//設置發信時間
message.setSentDate(new Date());

//存儲郵件信息
message.saveChanges();

//發送郵件
Transport transport=s.getTransport("smtp");
//以smtp方式登錄郵箱,第一個參數是發送郵件用的郵件伺服器SMTP地址,第二個參數為用戶名,第三個參數為密碼
transport.connect(Constant.mailServer,Constant.mailCount,Constant.mailPassword);
//發送郵件,其中第二個參數是所有已設好的收件人地址
transport.sendMessage(message,message.getAllRecipients());
transport.close();

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
//測試用的,你吧你想寫的內容寫上去就行
send(Constant.mailAddress,"收件人郵箱","標題","<b>內容</b>");
}
}

然後把mail.jar導入,就可以了,我用的是163 的,其他的吧相應的伺服器改一下就行了

㈨ 如何用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獲取資源。

㈩ 怎麼用JAVA實現郵件發送

用java mail 庫

閱讀全文

與java郵件相關的資料

熱點內容
dvdmark文件夾 瀏覽:203
廣聯達組價需要加密狗嗎 瀏覽:350
掛載分區命令 瀏覽:916
phpfpm的作用 瀏覽:653
填pdf表格 瀏覽:526
騰訊雲渲染伺服器 瀏覽:310
php內置異常 瀏覽:277
androidauto語音 瀏覽:55
雲繳費app兌換碼在哪裡 瀏覽:625
聖地安列斯安卓版存檔怎麼用 瀏覽:201
在哪裡可以找到舊版本的app 瀏覽:373
一個客戶端如何連接多個伺服器 瀏覽:883
簡訊加密的作用 瀏覽:108
微型高壓空氣壓縮機 瀏覽:520
微信app如何翻譯視頻 瀏覽:860
考試前聽什麼歌解壓 瀏覽:474
哪個app充值可以用銀聯二維碼 瀏覽:566
女程序員和孩子玩 瀏覽:839
程序員蘇州武漢 瀏覽:754
大腳插件如何切換安卓 瀏覽:943