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

java表格郵件

發布時間:2023-06-05 21:27:42

⑴ 用java寫一個郵件發送代碼

public boolean mainto()
{
boolean flag = true;

//建立郵件會話
Properties pro = new Properties();
pro.put("mail.smtp.host","smtp.qq.com");//存儲發送郵件的伺服器
pro.put("mail.smtp.auth","true"); //通過伺服器驗證

Session s =Session.getInstance(pro); //根據屬性新建一個郵件會話
//s.setDebug(true);

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

//設置郵件
InternetAddress fromAddr = null;
InternetAddress toAddr = null;

try
{
fromAddr = new InternetAddress(451144426+"@qq.com"); //郵件發送地址
message.setFrom(fromAddr); //設置發送地址

toAddr = new InternetAddress("[email protected]"); //郵件接收地址
message.setRecipient(Message.RecipientType.TO, toAddr); //設置接收地址

message.setSubject(title); //設置郵件標題
message.setText(content); //設置郵件正文
message.setSentDate(new Date()); //設置郵件日期

message.saveChanges(); //保存郵件更改信息

Transport transport = s.getTransport("smtp");
transport.connect("smtp.qq.com", "451144426", "密碼"); //伺服器地址,郵箱賬號,郵箱密碼
transport.sendMessage(message, message.getAllRecipients()); //發送郵件
transport.close();//關閉

}
catch (Exception e)
{
e.printStackTrace();
flag = false;//發送失敗
}

return flag;
}

這是一個javaMail的郵件發送代碼,需要一個mail.jar

⑵ 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實現發送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文檔。

⑷ java實現發送郵件功能

要實現郵件發送功能需要導入包:mail.jar

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package org.demo.action;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.demo.form.DemoForm;

public class DemoAction extends Action {

private static final String CONTENT_TYPE = "test/html;charset=GB2312";

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DemoForm demoForm = (DemoForm) form;
System.out.println("標題是" + demoForm.getBiaoti());
System.out.println("內容是" + demoForm.getNeirong());
try {
response.setContentType(CONTENT_TYPE);
String smtphost = "smtp.nj.headware.cn"; // 發送郵件伺服器
String user = "q0000015369"; // 郵件伺服器登錄用戶名
String password = "Queshuwen26"; // 郵件伺服器登錄密碼
String from = "[email protected]"; //
String to = "[email protected]"; // 收件人郵件地址
String subject = demoForm.getBiaoti(); // 郵件標題
String body = demoForm.getNeirong(); // 郵件內容
Properties props = new Properties();
props.put("mail.smtp.host", smtphost);
props.put("mail.smtp.auth", "true");
Session ssn = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(ssn);

InternetAddress fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = ssn.getTransport("smtp");

transport.connect(smtphost, user, password);

transport.sendMessage(message, message
.getRecipients(Message.RecipientType.TO));
// transport.send(message);
transport.close();
return mapping.findForward("succ");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("fail");
}

}
}

⑸ java如何實現復制excel中內容並粘貼到郵件發

主要是用到java裡面的i/o流。代碼例子如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
* java讀寫文件,復制文件
* 讀取d:/1.txt文件內容,寫入f:/text.txt文件中.
* @author young
*
*/
public class FileWriterTest {
// 讀寫文件
public static void rwFile(){
FileWriter fw = null;
BufferedReader br = null;
try {
fw = new FileWriter("f:\\text.txt", true);
br = new BufferedReader(new InputStreamReader(
new FileInputStream("d:\\1.txt"), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("文件內容: " + line);
fw.write(line);
fw.flush();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
rwFile();
}
}
首先在D盤新建文件1.txt,輸入任意內容。然後執行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 發送郵件,內容是要從資料庫中讀取的數據並列成表格的狀態發送出去

publicbooleansendTextMail(MailSenderInfomailInfo){
//判斷是否需要身份認證
MyAuthenticatorauthenticator=null;
Propertiespro=mailInfo.getProperties();
if(mailInfo.isValidate()){
//如果需要身份認證,則創建一個密碼驗證器
authenticator=newMyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());
}
//根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
SessionsendMailSession=null;


//sendMailSession=Session.getDefaultInstance(pro,authenticator);//獲取默認可能報錯
sendMailSession=Session.getInstance(pro,authenticator);//新創建一個session
if(sendMailSession==null){
System.out.println("無法獲取郵件郵件Session");
}
try{
//根據session創建一個郵件消息
MessagemailMessage=newMimeMessage(sendMailSession);
//創建郵件發送者地址
Addressfrom=newInternetAddress(mailInfo.getFromAddress());
//設置郵件消息的發送者
mailMessage.setFrom(from);
//創建郵件的接收者地址,並設置到郵件消息中
Addressto=newInternetAddress(mailInfo.getToAddress());

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

//設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
//設置郵件消息發送的時間
mailMessage.setSentDate(newDate());
//設置郵件消息的主要內容
StringmailContent=mailInfo.getContent();
mailMessage.setText(mailContent);//添加附件
//if(mailInfo.getAttachFileNames()!=null||mailInfo.getAttachFileNames().length>0){
//Multipartmp=newMimeMultipart();
//MimeBodyPartmbp=null;
//for(StringfileName:mailInfo.getAttachFileNames()){
//mbp=newMimeBodyPart();
//FileDataSourcefds=newFileDataSource(fileName);//得到數據源
//mbp.setDataHandler(newDataHandler(fds));//得到附件本身並至入BodyPart
//mbp.setFileName(fds.getName());//得到文件名同樣至入BodyPart
//mp.addBodyPart(mbp);
//}
//mailMessage.setContent(mp);
//}

//發送郵件
Transport.send(mailMessage);
returntrue;
}catch(MessagingExceptionex){
ex.printStackTrace();

}
returnfalse;
}
publicclassMailSenderInfo{
//發送郵件的伺服器的IP和埠
privateStringmailServerHost;
privateStringmailServerPort="25";
//郵件發送者的地址
privateStringfromAddress;
//郵件接收者的地址
privateStringtoAddress;
//登陸郵件發送伺服器的用戶名和密碼
privateStringuserName;
privateStringpassword;
//是否需要身份驗證
privatebooleanvalidate=false;
//郵件主題
privateStringsubject;
//郵件的文本內容
privateStringcontent;
//郵件附件的文件名
privateString[]attachFileNames;

//郵件抄送人

privateList<String>ccUserList;
/***//**
*獲得郵件會話屬性
*/
publicPropertiesgetProperties(){
Propertiesp=newProperties();
p.put("mail.smtp.host",this.mailServerHost);
p.put("mail.smtp.port",this.mailServerPort);
p.put("mail.smtp.auth",validate?"true":"false");
returnp;
}
publicStringgetMailServerHost(){
returnmailServerHost;
}
publicvoidsetMailServerHost(StringmailServerHost){
this.mailServerHost=mailServerHost;
}
publicStringgetMailServerPort(){
returnmailServerPort;
}
publicvoidsetMailServerPort(StringmailServerPort){
this.mailServerPort=mailServerPort;
}
publicbooleanisValidate(){
returnvalidate;
}
publicvoidsetValidate(booleanvalidate){
this.validate=validate;
}
publicString[]getAttachFileNames(){
returnattachFileNames;
}
publicvoidsetAttachFileNames(String[]fileNames){
this.attachFileNames=fileNames;
}
publicStringgetFromAddress(){
returnfromAddress;
}
publicvoidsetFromAddress(StringfromAddress){
this.fromAddress=fromAddress;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicStringgetToAddress(){
returntoAddress;
}
publicvoidsetToAddress(StringtoAddress){
this.toAddress=toAddress;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicStringgetSubject(){
returnsubject;
}
publicvoidsetSubject(Stringsubject){
this.subject=subject;
}
publicStringgetContent(){
returncontent;
}
publicvoidsetContent(StringtextContent){
this.content=textContent;
}
publicList<String>getCcUserList(){
returnccUserList;
}
publicvoidsetCcUserList(List<String>ccUserList){
this.ccUserList=ccUserList;
}


}

publicstaticvoidmain(String[]args){
//這個類主要是設置郵件
MailSenderInfomailInfo=newMailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("[email protected]");
mailInfo.setPassword("zzzong0828");//您的郵箱密碼
mailInfo.setFromAddress("");
//接受方信息
mailInfo.setToAddress("");
mailInfo.setSubject("郵箱標題");
mailInfo.setContent("設置郵箱內容如http://www.guihua.org中國桂花網是中國最大桂花網站==");

String[]files=newString[]{"D:/1.txt","D:/2.txt","D:/3.txt"};
mailInfo.setAttachFileNames(files);
//這個類主要來發送郵件
SimpleMailSendersms=newSimpleMailSender();
sms.sendTextMail(mailInfo);//發送文體格式
//sms.sendHtmlMail(mailInfo);//發送html格式
}



這樣發

閱讀全文

與java表格郵件相關的資料

熱點內容
京東文件夾英文名 瀏覽:658
冬天程序員面試穿搭女生 瀏覽:423
開會時如何發言app 瀏覽:941
手寫加密演算法java版 瀏覽:43
如何使用命令解壓rar 瀏覽:832
海爾之家app怎麼連接設備 瀏覽:854
高壓水槍壓槍解壓視頻 瀏覽:778
如何檢索遠程伺服器的ip地址 瀏覽:28
華為西安演算法中心 瀏覽:787
安卓什麼app的組件好看 瀏覽:550
外網伺服器地址誰有 瀏覽:192
計算三角形面積java 瀏覽:678
如何24小時開伺服器 瀏覽:729
靈動單片機的模擬設置 瀏覽:793
重慶監控伺服器雲主機 瀏覽:257
python環境模塊安裝 瀏覽:219
梧桐木和壓縮板的桌子哪個好 瀏覽:45
單片機註解 瀏覽:574
怎麼樣讓安卓系統更流暢 瀏覽:994
php抓取網頁圖片 瀏覽:82