- 論壇徽章:
- 0
|
import javax.mail.*; import javax.mail.internet.*;
import java.text.SimpleDateFormat;import java.util.*; import javax.activation.*; public class Mail { public static void main(String[] args) { Properties props = System.getProperties(); // 設(shè)置smtp服務(wù)器 props.setProperty("mail.smtp.host", "smtp.yicha.cn"); // 現(xiàn)在的大部分smpt都需要驗證了 props.put("mail.smtp.auth", "true"); Session s = Session.getInstance(props); // 為了查看運行時的信息 s.setDebug(true); // 由郵件會話新建一個消息對象 MimeMessage message = new MimeMessage(s); try { // 發(fā)件人 InternetAddress from = new InternetAddress("lgzbj2006@yahoo.com.cn"); //message.setFrom(from); // 收件人 InternetAddress to = new InternetAddress("renyiyong@yicha.cn"); InternetAddress to2 = new InternetAddress("liuhongwei@yicha.cn"); InternetAddress[] totest={to,to2}; //message.setRecipient(Message.RecipientType.TO, to); message.setRecipients(Message.RecipientType.TO,totest); // 郵件標(biāo)題 message.setSubject("test"); String content = "測試內(nèi)容"; // 郵件內(nèi)容,也可以使純文本"text/plain" message.setContent(content, "text/html;charset=GBK"); message.getReceivedDate(); /****下面代碼是發(fā)送附件****** */ String fileName = "d:\\hello.txt"; MimeBodyPart messageBodyPart = new MimeBodyPart(); SimpleDateFormat stringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E"); messageBodyPart.setText("問答元搜索,解析百度頁面出現(xiàn)問題,請及時處理\r\n"+"yicha.cn\r\n"+stringdate.format(new Date())); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileName); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.saveChanges(); Transport transport = s.getTransport("smtp"); // smtp驗證,就是你用來發(fā)郵件的郵箱用戶名密碼 transport.connect("smtp.yicha.cn", "renyiyong@yicha.cn", "yicha1"); // 發(fā)送 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); } } } 需要兩個jar包的下載地址:mail.jar 下載地址:
http://java.sun.com/products/javamail/downloads/index.html
activation.jar 下載地址:
http://java.sun.com/products/javabeans/jaf/downloads/index.html
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u3/104127/showart_2109617.html |
|