熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

java實現郵件的發送分享

2022-06-13   來源: Java核心技術 

  java實現郵件的發送分享方法如下

  public class PopupAuthenticator extends Authenticator{

  public PasswordAuthentication getPasswordAuthentication()

  {

  String username=;      //郵箱登錄帳號

  String pwd = ;         //登錄密碼

  return new PasswordAuthentication(usernamepwd)

  }

  }

  public class SendMail {

  public static void main(String[] args) {

  try {

  Authenticator auth = new PopupAuthenticator()

  Properties mailProps = new Properties()

  //郵件信息驗證

  mailPropsput(mailsmtphost

  mailPropsput(mailsmtpauth true

  mailPropsput(username   //用戶名

  mailPropsput(password //密碼

  Session mailSession = SessiongetDefaultInstance(mailProps auth)

  MimeMessage message = new MimeMessage(mailSession)

  messagesetFrom(new InternetAddress())//發件人地址

  Address toInternetAddress=new InternetAddress(//收件人地址

  messagesetRecipient(MessageRecipientTypeTO toInternetAddress)

  messagesetSubject(Mail Test  //郵件標題

  messagesetSentDate(new Date()) // 設置郵件發送日期

  MimeMultipart multi = new MimeMultipart()

  BodyPart textBodyPart = new MimeBodyPart()

  //textBodyPartsetText(Hello World! //郵件內容

  multiaddBodyPart(textBodyPart)

  messagesetContent(multi)

  messagesaveChanges()

  //下面代碼是發送附件

  String fileName = E:/hellotxt;  //發送附件的文件路徑

  MimeBodyPart messageBodyPart = new MimeBodyPart()

  messageBodyPartsetText(Hi there is message info      //郵件內容

  Multipart multipart = new MimeMultipart()

  multipartaddBodyPart(messageBodyPart)

  messageBodyPart = new MimeBodyPart()

  DataSource source = new FileDataSource(fileName)

  messageBodyPartsetDataHandler(new DataHandler(source))

  messageBodyPartsetFileName(fileName)

  multipartaddBodyPart(messageBodyPart)

  messagesetContent(multipart)

  //推送郵件和附件信息

  Transportsend(message)

  Systemoutprintln(郵件發送成功

  } catch (Exception ex) {

  Systemerrprintln(郵件發送失敗的原因是 + exgetMessage())

  Systemerrprintln(具體錯誤原因

  exprintStackTrace(Systemerr)

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/27084.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.