java mail郵件發送程序
package mail; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; 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 SendMail { private String mailServer, mailPort,username, password; private Session mailSession; private Properties prop; private Message message; /** * // 設置郵件服務器相關 */ public SendMail(String mailServer, String mailPort, String username, String password) { this.mailServer = mailServer; this.mailPort = mailPort; this.username = username; this.password = password; } /** * * @param to : [email protected]; * @param mailSubject: * @param mailContent */ public void send(String to, String mailSubject, String mailContent) { EmailAuthenticator mailauth = new EmailAuthenticator(username, password); // 設置郵件服務器 prop = System.getProperties(); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.host", mailServer); prop.put("mail.smtp.port", mailPort); // 產生新的Session服務 mailSession = mailSession.getDefaultInstance(prop, (Authenticator) mailauth); message = new MimeMessage(mailSession); try { message.setFrom(new InternetAddress(username)); // 設置發件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));// 設置收件人 message.setSubject(mailSubject);// 設置主題 // message.setContent(mailContent, "text/plain");// 設置內容,中文亂碼,用下面的方法 // 設置內容 Multipart multipart = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(mailContent); // mimeBodyPart.setFileName(MimeUtility.encodeText(mailContent, "GBK", "B")); //對郵件頭采用base64方式編碼 multipart.addBodyPart(mimeBodyPart); message.setContent(multipart); // 設置日期 message.setSentDate(new Date()); Transport tran = mailSession.getTransport("smtp"); tran.connect(mailServer, username, password); tran.send(message, message.getAllRecipients()); tran.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { SendMail mail; mail = new SendMail("222.74.xxx.xxx", "25", "[email protected]", "123456"); System.out.println("sending......"); mail.send("[email protected]", "Date:" + new Date().toLocaleString(), "eess1234"); System.out.println("finished!"); try{ Thread.sleep(5*1000L); } catch (Exception e) { e.printStackTrace(); } } }