『壹』 怎麼樣使用javaMail發送和接收郵件
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 = "xxxxx";
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();
}
}
}
『貳』 jsP中實現自動發送信息到郵箱謝謝了,大神幫忙啊
使用JAVAMAIL發送郵件~~ JavaMail是Sun的API之一,但它目前還沒有被加在標準的java開發工具包中(Java Development Kit),這就意味著你在使用前必須另外下載JavaMail文件。除此以外,你還需要有Sun的JavaBeans Activation Framework (JAF)。JavaBeans Activation Framework的運行很復雜,在這里簡單的說就是JavaMail的運行必須得依賴於它的支持。在Windows 2000下使用需要指定這些文件的路徑,在其它的操作系統上也類似。 接下來要講解的是這篇指南的最難理解的部分。 這篇指南包括三部分:HTML表格、關於JavaMail、JavaMail和JSP的結合。 第一部分:HTML表格 第一部分提供了一個最基本的基於HTML的email發送收取程序的例子。第二部分則講述JavaMail的工作原理。第三部分則介紹將JavaMail加入JSP,創建一個基本的email發送收取程序。 劃分組件 JSP最重要的特性是能將整個網頁劃分成一些細小的組件。這里使用的組件包括: ●一個用來將email的信息發送給JSP的HTML表格; ●一個JSP頁面用來處理和發送信件。 第一步,就是創建一個HTML表格用來給JSP頁面發送信息。你可以將以下的HTML代碼復制到你的電腦上: 用來發送email的HTML源代碼 <HTML> <BODY> <FORM action="sendmail.jsp" method="post"> <TABLE align="center"> <TR> <TD width="50%"> To:<BR><INPUT name="to" size="25"> </TD> <TD width="50%"> From:<BR><INPUT name="from" size="25"> </TD> </TR> <TR> <TD colspan="2"> Subject:<BR><INPUT name="subject" size="50"> </TD> </TR> <TR> <TD colspan="2"> Message:<BR><TEXTAREA name="text" rows=25 cols=85></TEXTAREA> </TD> </TR> </TABLE> <INPUT type="submit" name="cb_submit" value=" Send "> <INPUT type="reset" name="cb_reset" value=" Clear "> </FORM> </BODY> </HTML> 以上這段程序將創建一個包含email基本信息(例如:收件地址、發送地址、主題和內容)的文件。當然你可以根據你自己的需要來決定這個文件包含那些信息。 這個HTML文件的使用有兩點要求:第一點是生成的文件必須發送給接下來將介紹的程序使用。在這個例子中就是sendmail.jsp,但在你使用時,必須用這個文件在系統里的URL來代替它;第二點是必須有空間來允許用戶發送email。
『叄』 用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 mail 發送郵件例子 源代碼
暈,貌似這個問題以前有人提過,我也回答過了,不滿意嗎?需要用到javamail的jar包,網上有。找不到把郵箱貼出來,我發給你。package test.servlet;import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class SendMailServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2960000940515881314L;
private ServletConfig config = null;
private static final String CONTENT_TYPE = "text/html";public void init(ServletConfig config1) throws ServletException {
this.config = config1;
}final public ServletConfig getServletConfig() {
return config;
}/**
* Constructor of the object.
*/
public SendMailServlet() {
super();
}/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
}/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String to_mail=codeToString(request.getParameter("to"));
String to_title=codeToString(request.getParameter("title"));
String to_content=codeToString(request.getParameter("content"));
Properties props=new Properties();//也可用Properties props = System.getProperties(); //
props.put("mail.smtp.host","localhost");//存儲發送郵件伺服器的信息
props.put("mail.smtp.auth","true");//同時通過驗證
Session s=Session.getInstance(props);//根據屬性新建一個郵件會話
s.setDebug(true);//由郵件會話新建一個消息對象
MimeMessage message=new MimeMessage(s);//由郵件會話新建一個消息對象//設置郵件
InternetAddress from;
try {
from = new InternetAddress("[email protected]");
message.setFrom(from);//設置發件人
InternetAddress to=new InternetAddress(to_mail);
message.setRecipient(Message.RecipientType.TO,to);//設置收件人,並設置其接收類型為TO
message.setSubject(to_title);//設置主題
message.setText(to_content);//設置信件內容
message.setSentDate(new Date());//設置發信時間
//發送郵件
message.saveChanges();//存儲郵件信息
Transport transport=s.getTransport("smtp");
//以smtp方式登錄郵箱,第一個參數是發送郵件用的郵件伺服器SMTP地址,第二個參數為用戶名,第三個參數為密碼
transport.connect("localhost",8479,"","");
transport.sendMessage(message,message.getAllRecipients());//發送郵件,其中第二個參數是所有已設好的收件人地址
transport.close();
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.print("success");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}}
public String codeToString(String str) {//處理中文字元串的函數
String s=str;
try {
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
} catch(Exception e) {
return s;
}
}
}
『伍』 如何用javamail定時發送郵件
不知道是怎樣的使用環境了,,,,,,,,,一般JAVA都可以用定時器實現定時 、、定期 。。。。。。。。。。。。。
『陸』 javamail中message.setSentDate(date)方法,意思是定時發送嗎
這個是設置發送時間的方法,但不是定時發送。
比如你發送郵件時用該方法設置一個時間,那麼這個郵件顯示的發送時間就是你設置的時間。
『柒』 java中如何實現公司郵箱發送郵件配置
Java中可以通過Javamail API實現公司郵箱郵件發送配置,Java mail是利用現有的郵箱賬戶發送郵件的版工具,具體步權驟如如下:
1、通過JavamailAPI設置發送者郵箱用戶名及密碼
2、通過JavamailAPI設置郵件主題、郵件內容、附件及郵件發送時間
3、通過JavamailAPI設置發送者郵箱地址及接收者郵箱地址,接收者地址可以是多個及抄送
4、郵件的需基本元素都設置完畢後,即可通過Javamail API的發送介面執行發送操作。
『捌』 JavaMail發送郵件代碼
importjava.io.UnsupportedEncodingException;
importjava.util.Date;
importjava.util.Properties;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.NoSuchProviderException;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
publicclassMailUtil{
staticintport=25;
staticStringserver="smtp.sina.com";//郵件伺服器mail.cpip.net.cn
staticStringfrom="張三";//發送者,顯示的發件人名字
staticStringuser="[email protected]";//發送者郵箱地址
staticStringpassword="***********";//密碼
publicstaticvoidsendEmail(Stringemail,Stringsubject,Stringbody){
try{
Propertiesprops=newProperties();
props.put("mail.smtp.host",server);
props.put("mail.smtp.port",String.valueOf(port));
props.put("mail.smtp.auth","true");
Transporttransport=null;
Sessionsession=Session.getDefaultInstance(props,null);
transport=session.getTransport("smtp");
transport.connect(server,user,password);
MimeMessagemsg=newMimeMessage(session);
msg.setSentDate(newDate());
InternetAddressfromAddress=newInternetAddress(user,from,"UTF-8");
msg.setFrom(fromAddress);
InternetAddress[]toAddress=newInternetAddress[1];
toAddress[0]=newInternetAddress(email);
msg.setRecipients(Message.RecipientType.TO,toAddress);
msg.setSubject(subject,"UTF-8");
msg.setText(body,"UTF-8");
msg.saveChanges();
transport.sendMessage(msg,msg.getAllRecipients());
}catch(NoSuchProviderExceptione){
e.printStackTrace();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(Stringargs[])
{
sendEmail("[email protected]","郵件測試","hello");//收件人
System.out.println("ok");
}
}