JAVA中寄送電子郵件的方法

來源:互聯網
上載者:User

標籤:方法   rgs   ssi   str   public   檔案   pat   pie   文本   

   JAVA中發送郵件的方法不複雜,使用sun的JavaMail的架包就可以實現。

 

 一、下載JavaMail的架包,並匯入項目中,如下:

 

二、附上代碼例子,如下:

1、在main函數中對各項參數進行賦值(參數說明已進行備忘),即可通過send函數進行發送郵件操作。

 1 public class TestEmail { 2  3     private final static String TIMEOUT_MS = "20000"; 4  5     public static void main(String[] args) { 6         String host = "smtp.exmail.qq.com"; 7         String user = "[email protected]"; 8         String password = "xxxxxx"; 9         String recipients = "[email protected]";10         String cc = "";11         String subject = "郵件發送測試";12         String content = "郵件內文:<br>你好!";13         //方式1:通過URL擷取附件14 //        byte[] attachment = FileUtil.getFileByUrl("http://127.0.0.1/project/test.pdf");15         //方式2:通過本地路徑擷取附件16         byte[] attachment = FileUtil.getFileByPath("c://fujian.pdf");17         18         String attachmentName = "";19         try {20             attachmentName = MimeUtility.encodeWord("這是附件.pdf");21             send(host, user, password, recipients, cc, subject, content, attachment, attachmentName);22         } catch (Exception e) {23             e.printStackTrace();24         }25     }26     27     /**28      * @param host 郵件伺服器主機名稱29      * @param user 使用者名稱30      * @param password 密碼31      * @param recipients 收件者32      * @param cc 抄送人33      * @param subject 主題34      * @param content 內容35      * @param attachment 附件 [沒有傳 null]36      * @param attachmentName 附件名稱 [沒有傳 null]37      * @throws Exception38      */39     public static void send(final String host, final String user, final String password,40                      final String recipients, final String cc, final String subject, final String content,41                      final byte[] attachment,final String attachmentName) throws Exception {42         Properties props = new Properties();43         props.put("mail.smtp.host", host);44         props.put("mail.smtp.auth", "true");45         props.put("mail.smtp.timeout", TIMEOUT_MS);46 47         Authenticator auth = new Authenticator() {48             @Override49             protected PasswordAuthentication getPasswordAuthentication() {50                 return new PasswordAuthentication(user, password);51             }52         };53         Session session = Session.getInstance(props, auth);54         MimeMessage msg = new MimeMessage(session);55         msg.setFrom(new InternetAddress(user));56         msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));57         if (cc != null && cc.length() > 0) {58             msg.setRecipients(Message.RecipientType.CC, cc);59         }60         msg.setSubject(subject);61         // 向multipart對象中添加郵件的各個部分內容,包括常值內容和附件62         Multipart multipart = new MimeMultipart();63         // 添加郵件內文64         BodyPart contentPart = new MimeBodyPart();65         contentPart.setContent(content, "text/html;charset=UTF-8");66         multipart.addBodyPart(contentPart);67         // 添加附件的內容68         if (attachment!=null) {69             BodyPart attachmentBodyPart = new MimeBodyPart();70             DataSource source = new ByteArrayDataSource(attachment,"application/octet-stream");71             attachmentBodyPart.setDataHandler(new DataHandler(source));72             //MimeUtility.encodeWord可以避免檔案名稱亂碼73             attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachmentName));74             multipart.addBodyPart(attachmentBodyPart);75         }76         // 將multipart對象放到message中77         msg.setContent(multipart);78         // 儲存郵件79         msg.saveChanges();80         Transport.send(msg, msg.getAllRecipients());81     }82 }

 

2、上面的例子中,如果有附件,可對附件進行設定。附件的擷取這裡舉2個例子,方式1通過網址擷取,方式2通過本地擷取。附上擷取附件檔案的方法,如下:

 1 public class FileUtil { 2  3     public static byte[] getFileByUrl(String urlStr){ 4         try { 5             URL url = new URL(urlStr); 6             HttpURLConnection conn = (HttpURLConnection) url.openConnection();             7             InputStream is = conn.getInputStream();   8             BufferedInputStream bis = new BufferedInputStream(is);   9             ByteArrayOutputStream baos = new ByteArrayOutputStream();  10             final int BUFFER_SIZE = 2048;11             final int EOF = -1;  12             int c;  13             byte[] buf = new byte[BUFFER_SIZE];  14             while (true) {  15                 c = bis.read(buf);  16                 if (c == EOF)  17                     break;  18                 baos.write(buf, 0, c);  19             }  20             conn.disconnect();  21             is.close();  22       23             byte[] data = baos.toByteArray();  24             baos.flush();25             return data;26             27         } catch (Exception e) {28             e.printStackTrace();29         }30         return null;31     }32     33     public static byte[] getFileByPath(String pathStr){34         File file = new File(pathStr);35         try {36             FileInputStream fis = new FileInputStream(file);37             ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);38             byte[] b = new byte[1000];39             int n;40             while ((n = fis.read(b)) != -1) {41                 bos.write(b, 0, n);42             }43             fis.close();44             byte[] data = bos.toByteArray();45             bos.close();46             return data;47         } catch (Exception e) {48             e.printStackTrace();49         }50         return null;51     }52 }

 

JAVA中寄送電子郵件的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.