JAva送信の簡単な例

5600 ワード

package OSChina;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Authenticator;

import javax.mail.Message;

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;

/**
 *
 * <p>
 * Description:use the javamail to send email!Must use sun's mail.jar,no apache
 * jar.
 * </p>
 *
 * @author
 */

public class SendMail {

	public static void main(String[] args) {

		SendMail sendMail = new SendMail("[email protected]",
				"[email protected]", "smtp.126.com", "username",

				"password", "  Java Mail", "  ,Javamail!   !");

		//     

		sendMail.addAttachment("D:/english.txt");

		// sendMail.addAttachment("D://IOTest.java");

		if (sendMail.send()) {

			System.out.println("Successful!");

		}

	}

	private String to; //    

	private String from; //    

	private String smtpServer; // smtp  .

	private String userName;

	private String password;

	private String subject;

	private String content;

	//            ,       

	List<String> attachments = new ArrayList<String>();

	public SendMail(String to, String from, String smtpServer, String userName,
			String password, String subject,

			String content) {

		this.to = to;

		this.from = from;

		this.smtpServer = smtpServer;

		this.userName = userName;

		this.password = password;

		this.subject = subject;

		this.content = content;

	}

	//          ,           ,QQ   UTF-8. GBK.GB2312    .

	public String translateChinese(String strText) {

		try {

			// MimeUtility.encodeText(String text, String charset, String

			// encoding) throws java.io.UnsupportedEncodingException

			// text    . charset    。       null,           。

			// encoding       。        "B"   "Q"。       null,          ASCII

			//          "Q"   ;       "B"   。

			strText = MimeUtility.encodeText(new String(strText.getBytes(),
					"UTF-8"), "UTF-8", "B");

		} catch (Exception e) {

			e.printStackTrace();

		}

		return strText;

	}

	//     

	public void addAttachment(String fname) {

		attachments.add(fname);

	}

	public boolean send() {

		//     Session   Properties  .API    set   put(putall).

		Properties props = new Properties();

		props.setProperty("mail.smtp.host", smtpServer);

		props.setProperty("mail.smtp.auth", "true");

		//   Session  ,  JavaMail        .

		// Authenticator==>Java mail     , QQ        .       ,  .

		// PasswordAuthentication==>       .     ,            .

		Session session = Session.getDefaultInstance(props,

		new Authenticator() {

			public PasswordAuthentication getPasswordAuthentication() {

				return new PasswordAuthentication(userName, password);

			}

		}

		);

		try {

			//   MimeMessage        ,MimeMessage           .

			MimeMessage msg = new MimeMessage(session);

			//      

			msg.setFrom(new InternetAddress(from));

			//      ,   ,       .

			InternetAddress[] addresses = { new InternetAddress(to) };

			// Message.RecipientType==>TO(     ),CC(  ),BCC(    )

			msg.setRecipients(Message.RecipientType.TO, addresses);

			//       ,    UTF-8     .

			// subject=translateChinese(subject);

			msg.setSubject(subject);

			// =====================    ===========

			//   Multipart  

			Multipart mp = new MimeMultipart();

			// =====================      ===========

			//  Multipart    

			MimeBodyPart mbpContent = new MimeBodyPart();

			mbpContent.setText(content);

			//  BodyPart   MultiPart   

			mp.addBodyPart(mbpContent);

			// =====================      ===========

			//  MulitPart    ,      ,             

			for (String efile : attachments) {

				MimeBodyPart mbpFile = new MimeBodyPart();

				//       FileDataSource  

				FileDataSource fds = new FileDataSource(efile);

				//     

				mbpFile.setDataHandler(new DataHandler(fds));

				mbpFile.setFileName(fds.getName());

				//  BodyPart   Multipart   

				mp.addBodyPart(mbpFile);

			}

			attachments.clear();

			//  MimeMessage  Multipart

			msg.setContent(mp);

			msg.setSentDate(new Date());

			//     ,      !

			Transport.send(msg);

		} catch (Exception e) {

			e.printStackTrace();

			return false;

		}

		return true;

	}

	public String getTo() {

		return to;

	}

	public void setTo(String to) {

		this.to = to;

	}

	public String getFrom() {

		return from;

	}

	public void setFrom(String from) {

		this.from = from;

	}

	public String getSmtpServer() {

		return smtpServer;

	}

	public void setSmtpServer(String smtpServer) {

		this.smtpServer = smtpServer;

	}

	public String getUserName() {

		return userName;

	}

	public void setUserName(String userName) {

		this.userName = userName;

	}

	public String getPassword() {

		return password;

	}

	public void setPassword(String password) {

		this.password = password;

	}

	public String getSubject() {

		return subject;

	}

	public void setSubject(String subject) {

		this.subject = subject;

	}

	public String getContent() {

		return content;

	}

	public void setContent(String content) {

		this.content = content;

	}


}