❶ 用java來發送帶附件的郵件
用java來發送帶附件的郵件要翻譯的。
❷ 急java 發送郵件 急!~急!~ 高手快進來幫忙看看啊!~
這是我的連續發幾封郵件的代碼。連續發是為了163郵箱的積分,^_^。你可以參考下。
package com.test;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail extends Authenticator {
public static final String mailuser = "xianlaioy"; // 需要你的郵箱帳號(僅@符號前面的)
public static final String password = "######"; // 需要你的郵箱密碼
private Properties props;
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailuser, password);
}
public SendEmail(){
props = new Properties();
InputStream is = null;
try {
/*當部署在web容器中時,路徑要修改
* Thread.currentThread().getContextClassLoader().getResource("").getPath();
* 得到的url是web容器中的項目下的class路徑
**/
is = new FileInputStream("src/sendemail.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/** email為接收郵箱,text為郵件正文
* @throws IOException */
public void sendEamils(String email, String text) throws IOException {
Transport transport = null;
try {
props.setProperty("mail.smtp.host", props.getProperty("mail.smtp.host"));
props.setProperty("mail.smtp.auth", props.getProperty("mail.smtp.auth"));
SendEmail auth = new SendEmail();
javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,
auth);
MimeMessage message = new MimeMessage(session);
Address addressFrom = new InternetAddress(SendEmail.mailuser
+ "@163.com", "歐陽");
Address addressTo = new InternetAddress(email, "xianlai");
message.setText(text);
message.setSubject("郵件標題");
message.setFrom(addressFrom);
message.addRecipient(Message.RecipientType.TO, addressTo);
message.saveChanges();
transport = session.getTransport("smtp");
session.setDebug(true);
/*transport.connect("smtp.126.com", SendEmail.mailuser,
SendEmail.password);*/
transport.send(message);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Timer t = new Timer();
long delay =2*60*1000;
t.schele(new TimerTask(){
private int count=0;
private SendEmail se=new SendEmail();//作為成員變數就只會創建一個SendEmail對象。
public void run() {
//在timer的run中就必須考慮好怎樣或者什麼時候退出的問題。
//這里是用count計數的方法來考慮退出的問題的。
if(count++<1){
int i=10;
for (int j = 0; j < i; j++) {
try {
se.sendEamils("[email protected]","test"+j );
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
this.cancel();
System.exit(0);
}
}}, 2000,delay);
}
}
❸ java里如何判斷Email是否發送成功
package com.liuns.mail.test;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
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 MailTest {
//發送的郵箱 內部代碼只適用qq郵箱
private static final String USER = "[email protected]";
//授權密碼 通過QQ郵箱設置->賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務->開啟POP3/SMTP服務獲取
private static final String PWD = "xxx";
private String[] to;
private String[] cc;//抄送
private String[] bcc;//密送
private String[] fileList;//附件
private String subject;//主題
private String content;//內容,可以用html語言寫
public void sendMessage() throws Exception {
// 配置發送郵件的環境屬性
final Properties props = new Properties();
//下面兩段代碼是設置ssl和埠,不設置發送不出去。
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
// 表示SMTP發送郵件,需要進行身份驗證
props.setProperty("mail.transport.protocol", "smtp");// 設置傳輸協議
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");//QQ郵箱的伺服器 如果是企業郵箱或者其他郵箱得更換該伺服器地址
// 發件人的賬號
props.put("mail.user", USER);
// 訪問SMTP服務時需要提供的密碼
props.put("mail.password", PWD);
// 構建授權信息,用於進行SMTP進行身份驗證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用戶名、密碼
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用環境屬性和授權信息,創建郵件會話
Session mailSession = Session.getInstance(props, authenticator);
// 創建郵件消息
MimeMessage message = new MimeMessage(mailSession);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// 設置發件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
//發送
if (to != null) {
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
message.setRecipients(RecipientType.TO, iaToList); // 收件人
}
//抄送
if (cc != null) {
String toListcc = getMailList(cc);
InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);
message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人
}
//密送
if (bcc != null) {
String toListbcc = getMailList(bcc);
InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);
message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人
}
message.setSentDate(new Date()); // 發送日期 該日期可以隨意寫,你可以寫上昨天的日期(效果很特別,親測,有興趣可以試試),或者抽象出來形成一個參數。
message.setSubject(subject); // 主題
message.setText(content); // 內容
//顯示以html格式的文本內容
messageBodyPart.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
//保存多個附件
if(fileList!=null){
addTach(fileList, multipart);
}
message.setContent(multipart);
// 發送郵件
Transport.send(message);
}
public void setTo(String[] to) {
this.to = to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFileList(String[] fileList) {
this.fileList = fileList;
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
//添加多個附件
public void addTach(String fileList[], Multipart multipart) throws Exception {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
multipart.addBodyPart(mailArchieve);
}
}
//以下是演示demo
public static void main(String args[]) {
MailTest mail = new MailTest();
mail.setSubject("java郵件");
mail.setContent("你好 這是第一個java 程序發送郵件");
//收件人 可以發給其他郵箱(163等) 下同
mail.setTo(new String[] {"[email protected]"});
//抄送
// mail.setCc(new String[] {"[email protected]","[email protected]"});
//密送
//mail.setBcc(new String[] {"[email protected]","[email protected]"});
//發送附件列表 可以寫絕對路徑 也可以寫相對路徑(起點是項目根目錄)
// mail.setFileList(new String[] {"D:\\aa.txt"});
//發送郵件
try {
mail.sendMessage();
System.out.println("發送郵件成功!");
} catch (Exception e) {
System.out.println("發送郵件失敗!");
e.printStackTrace();
}
}
}
❹ java中如何實現公司郵箱發送郵件配置
Java中可以通過Javamail API實現公司郵箱郵件發送配置,Java mail是利用現有的郵箱賬戶發送郵件的版工具,具體步權驟如如下:
1、通過JavamailAPI設置發送者郵箱用戶名及密碼
2、通過JavamailAPI設置郵件主題、郵件內容、附件及郵件發送時間
3、通過JavamailAPI設置發送者郵箱地址及接收者郵箱地址,接收者地址可以是多個及抄送
4、郵件的需基本元素都設置完畢後,即可通過Javamail 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發送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實現發送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發送郵件could not connect to smtp host port 25
這個錯誤是連不上郵件伺服器的25埠。
1,檢查郵件伺服器是否正常,檢查IP和埠是否寫對。
2,檢查你的主機到郵件伺服器網路是否正常,可以用PING 或 TELNET IP PORT來測試。
❾ 用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