Thursday, November 13, 2014

Code nhỏ gởi email với java

Sử dụng thư viện mail của Java và tài khoản gmail để gởi thư điên.

1 package javamaildemo;
2 import java.util.Properties;
3 import java.util.logging.Level;
4 import java.util.logging.Logger;
5 import javax.mail.Authenticator;
6 import javax.mail.Folder;
7 import javax.mail.Message;
8 import javax.mail.PasswordAuthentication;
9 import javax.mail.Session;
10 import javax.mail.Store;
11 import javax.mail.Transport;
12 import javax.mail.internet.InternetAddress;
13 import javax.mail.internet.MimeMessage;
14
15 public class JavaMailDemo {
16 public static void main(String[] args) {
17 try {
18 // Authenticated and send mail
19 Properties props = System.getProperties();
20 props.put("mail.smtp.host", "smtp.gmail.com");
21 props.put("mail.smtp.port", "587");
22 props.put("mail.transport.protocol", "smtp");
23 props.put("mail.smtp.starttls.enable", "true");
24 props.put("mail.smtp.auth", "true");
25 props.put("mail.debug", "true");
26
27 Authenticator auth;
28 auth = new Authenticator() {
29 public PasswordAuthentication getPasswordAuthentication() {
30 return new PasswordAuthentication("ngotuongdan04@gmail.com", "ngotuongdan");
31 }
32 };
33
34 Session session = Session.getInstance(props, auth);
35 Message msg = new MimeMessage(session);
36
37 msg.setFrom(new InternetAddress("ngotuongdan04@gmail.com"));
38 msg.setSubject("Java mail demo");
39 msg.setRecipient(Message.RecipientType.TO, new InternetAddress("ntdan@ctu.edu.vn"));
40 msg.setContent("<h1>Hello ! How are you ?</h1>", "text/html");
41
42 Transport.send(msg);
43
44 /* check mail
45
46 props.put("mail.pop3.host", "pop.gmail.com");
47 props.put("mail.pop3.starttls.enable", "true");
48 props.put("mail.debug", "true");
49 props.put("mail.transport.protocol", "pop3");
50 props.put("mail.pop3.port", "995");
51
52 Session session = Session.getInstance(props);
53
54 Store stored = session.getStore("pop3");
55 stored.connect("pop.gmail.com",995,"ngotuongdan04@gmail.com", "ngotuongdan");
56 Folder folder = stored.getDefaultFolder();
57 folder.open(Folder.READ_ONLY);
58 System.out.print(folder.getMessageCount());
59 */
60 } catch (Exception ex) {
61 System.out.print(ex.toString());
62 }
63 }
64 }
65

Cần phải tham chiếu thêm thư viện mail.jar vào ứng dụng.

2 comments:

  1. nều dùng đoạn mã trên vậy việc public pass email thì bị mất email sao admin?

    ReplyDelete
  2. Day la demo cho sinh vien lop toi day ban a, va day la mail dung test, thuc te khi gan vao ung dung thi se can phai che di (co nhieu cach)

    ReplyDelete

Translate