㈠ java Mail發送郵件
連接的錯誤,smtp是需要登錄伺服器的使用的是base64的編碼格式。沒有代碼也不太清楚 你哪裡錯了
㈡ 使用javaMailSender發送郵件
郵件
㈢ 怎樣用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發送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("[email protected]"));
//設置收件人地址 message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress("[email protected]") });
//設置郵件標題
message.setSubject("這是第一封Java郵件");
//設置郵件內容
message.setText("內容為: 這是第一封java發送來的郵件。");
//得到郵差對象
Transport transport = session.getTransport();
//連接自己的郵箱賬戶
transport.connect("[email protected]", "vvctybgbvvophjcj");//密碼為剛才得到的授權碼
//發送郵件 transport.sendMessage(message, message.getAllRecipients());
}
}
10.運行就會發出郵件了。。。。
下面是我收到郵件的截圖,當然我把源碼中的郵件地址都是修改了,不是真實的,你們測試的時候,可以修改能你們自己的郵箱。最後,祝你也能成功,如果有什麼問題,可以一起討論!
注意事項
得到的授權碼一定要保存好,程序中要使用
㈤ 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獲取資源。
㈧ 如何用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實現郵件發送
用java mail 庫
㈩ 怎樣用java發送郵件
首先下載 JavaMail jar 包,並導入到項目中。下載地址
編寫代碼,代碼如下:
importjavax.mail.Authenticator;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
publicclassApp45{
publicstaticvoidmain(String[]args)throwsAddressException,MessagingException{
Propertiesproperties=System.getProperties();
properties.setProperty("mail.smtp.host","郵件發送伺服器");
properties.setProperty("mail.smtp.auth","true");
Sessionsession=Session.getDefaultInstance(properties,newAuthenticator(){
@Override
(){
//設置發件人郵件帳號和密碼
("郵件帳號","密碼");
}
});
MimeMessagemessage=newMimeMessage(session);
//設置發件人郵件地址
message.setFrom(newInternetAddress("發件人郵件地址"));
//設置收件人郵件地址
message.addRecipient(Message.RecipientType.TO,newInternetAddress("收件人郵件地址"));
message.setSubject("這里是郵件主題。");
message.setText("這里是郵件內容。");
Transport.send(message);
}
}