2008-09-05 71 views
179

Có thể gửi email từ ứng dụng Java của tôi bằng tài khoản Gmail không? Tôi đã cấu hình máy chủ thư công ty của tôi với ứng dụng Java để gửi email, nhưng điều đó sẽ không cắt nó khi tôi phân phối ứng dụng. Câu trả lời với bất kỳ việc sử dụng Hotmail, Yahoo hoặc GMail đều được chấp nhận.Làm cách nào để gửi email bằng ứng dụng Java bằng Gmail, Yahoo hoặc Hotmail?

Trả lời

163

Đầu tiên tải về JavaMail API và đảm bảo các tệp jar có liên quan nằm trong đường dẫn lớp của bạn.

Đây là ví dụ hoạt động đầy đủ khi sử dụng Gmail.

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 

public class Main { 

    private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") 
    private static String PASSWORD = "********"; // GMail password 
    private static String RECIPIENT = "[email protected]"; 

    public static void main(String[] args) { 
     String from = USER_NAME; 
     String pass = PASSWORD; 
     String[] to = { RECIPIENT }; // list of recipient email addresses 
     String subject = "Java send mail example"; 
     String body = "Welcome to JavaMail!"; 

     sendFromGMail(from, pass, to, subject, body); 
    } 

    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { 
     Properties props = System.getProperties(); 
     String host = "smtp.gmail.com"; 
     props.put("mail.smtp.starttls.enable", "true"); 
     props.put("mail.smtp.host", host); 
     props.put("mail.smtp.user", from); 
     props.put("mail.smtp.password", pass); 
     props.put("mail.smtp.port", "587"); 
     props.put("mail.smtp.auth", "true"); 

     Session session = Session.getDefaultInstance(props); 
     MimeMessage message = new MimeMessage(session); 

     try { 
      message.setFrom(new InternetAddress(from)); 
      InternetAddress[] toAddress = new InternetAddress[to.length]; 

      // To get the array of addresses 
      for(int i = 0; i < to.length; i++) { 
       toAddress[i] = new InternetAddress(to[i]); 
      } 

      for(int i = 0; i < toAddress.length; i++) { 
       message.addRecipient(Message.RecipientType.TO, toAddress[i]); 
      } 

      message.setSubject(subject); 
      message.setText(body); 
      Transport transport = session.getTransport("smtp"); 
      transport.connect(host, from, pass); 
      transport.sendMessage(message, message.getAllRecipients()); 
      transport.close(); 
     } 
     catch (AddressException ae) { 
      ae.printStackTrace(); 
     } 
     catch (MessagingException me) { 
      me.printStackTrace(); 
     } 
    } 
} 

Đương nhiên, bạn sẽ muốn làm nhiều hơn nữa trong catch khối so với in stack trace như tôi đã làm trong đoạn code ví dụ trên. (Tháo catch khối để xem phương thức các cuộc gọi từ các ngoại lệ API ném JavaMail vì vậy bạn tốt hơn có thể tham khảo cách xử lý đúng đắn họ.)


Nhờ @jodonnel và tất cả mọi người đã trả lời. Tôi đang cho anh ta một tiền thưởng vì câu trả lời của anh ấy đã dẫn tôi tới 95% con đường đến một câu trả lời hoàn chỉnh.

+0

con thằn lằn - chúng ta có cần chuyển tiếp cổng này không ??? props.put ("mail.smtp.port", "587"); cổng này phải được mở? – Varun

+1

@varun: Đó là cổng trên máy chủ thư đi, 'smtp.gmail.com'. Xem [Định cấu hình ứng dụng thư khách khác] (http://mail.google.com/support/bin/answer.py?answer=13287) để biết chi tiết. –

+1

Tôi là người duy nhất nhận được AuthenticationFailedException ở đây props.put ("mail.smtp.auth", "true"); nếu đúng là chuỗi. Nó là tốt nếu nó là một boolean. – nyxz

0

Một tuyến đường dễ dàng là phải bật/bật tài khoản gmail để truy cập POP3. Điều này sẽ cho phép bạn gửi qua SMTP thông thường thông qua các máy chủ gmail.

Sau đó, bạn sẽ chỉ cần gửi qua smtp.gmail.com (trên cổng 587)

106

Something như thế này (có vẻ như bạn chỉ cần thay đổi máy chủ SMTP của bạn):

String host = "smtp.gmail.com"; 
String from = "user name"; 
Properties props = System.getProperties(); 
props.put("mail.smtp.host", host); 
props.put("mail.smtp.user", from); 
props.put("mail.smtp.password", "asdfgh"); 
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail 
props.put("mail.smtp.auth", "true"); 

Session session = Session.getDefaultInstance(props, null); 
MimeMessage message = new MimeMessage(session); 
message.setFrom(new InternetAddress(from)); 

InternetAddress[] to_address = new InternetAddress[to.length]; 
int i = 0; 
// To get the array of addresses 
while (to[i] != null) { 
    to_address[i] = new InternetAddress(to[i]); 
    i++; 
} 
System.out.println(Message.RecipientType.TO); 
i = 0; 
while (to_address[i] != null) { 

    message.addRecipient(Message.RecipientType.TO, to_address[i]); 
    i++; 
} 
message.setSubject("sending in a group"); 
message.setText("Welcome to JavaMail"); 
// alternately, to send HTML mail: 
// message.setContent("<p>Welcome to JavaMail</p>", "text/html"); 
Transport transport = session.getTransport("smtp"); 
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh"); 
transport.sendMessage(message, message.getAllRecipients()); 
transport.close(); 
+0

Có thể gửi nội dung dưới dạng html không? Nếu tôi cố gắng viết một số mã html và gửi nó, nhưng trên đầu nhận, nội dung của email chỉ là mã html. –

+4

Để gửi nội dung html thay vì thay đổi văn bản rõ ràng dòng này: 'message.setText (" Chào mừng bạn đến với JavaMail ");' với dòng này: 'message.setContent ("

Xin chào thế giới

"," text/html ");' – mist

+4

Cái này bị thiếu ("mail.smtp.starttls.enable", "true") – Sotomajor

13

Mặc dù câu hỏi này được đóng lại, tôi muốn gửi một giải pháp truy cập, nhưng bây giờ sử dụng Simple Java Mail (Open Source JavaMail smtp wrapper):

final Email email = new Email(); 

String host = "smtp.gmail.com"; 
Integer port = 587; 
String from = "username"; 
String pass = "password"; 
String[] to = {"[email protected]"}; 

email.setFromAddress("", from); 
email.setSubject("sending in a group"); 
for(int i=0; i < to.length; i++) { 
    email.addRecipient("", to[i], RecipientType.TO); 
} 
email.setText("Welcome to JavaMail"); 

new Mailer(host, port, from, pass).sendMail(email); 
// you could also still use your mail session instead 
new Mailer(session).sendMail(email); 
+2

Tôi gặp lỗi với mã đó: "Thông báo: Lỗi chung: 530 5.7.0 Phải đưa ra lệnh STARTTLS trước" - làm thế nào để bạn bật starttls bằng vesijama? – iddqd

+1

Tôi đã nhận được lỗi "Phải phát hành một STARTTLS đầu tiên" vì trong dòng dưới đây tôi đã có biến isStartTlsEnabled dưới dạng boolean, thay vào đó là String: props.put ("mail.smtp.starttls.enable", isStartTlsEnabled); – user64141

+0

Từ [câu trả lời này] (http://stackoverflow.com/a/31974869/441662): Để sử dụng TLS, bạn có thể làm một cái gì đó như 'Mailer mới (đăng nhập của bạn/phiên của bạn, TransportStrategy.SMTP_TLS) .sendMail (email) ; ' –

1

Đây là những gì tôi làm khi tôi muốn gửi email có tệp đính kèm, hoạt động tốt. :)

public class NewClass { 

    public static void main(String[] args) { 
     try { 
      Properties props = System.getProperties(); 
      props.put("mail.smtp.starttls.enable", "true"); 
      props.put("mail.smtp.host", "smtp.gmail.com"); 
      props.put("mail.smtp.auth", "true"); 
      props.put("mail.smtp.port", "465"); // smtp port 
      Authenticator auth = new Authenticator() { 

       @Override 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication("username-gmail", "password-gmail"); 
       } 
      }; 
      Session session = Session.getDefaultInstance(props, auth); 
      MimeMessage msg = new MimeMessage(session); 
      msg.setFrom(new InternetAddress("[email protected]")); 
      msg.setSubject("Try attachment gmail"); 
      msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); 
      //add atleast simple body 
      MimeBodyPart body = new MimeBodyPart(); 
      body.setText("Try attachment"); 
      //do attachment 
      MimeBodyPart attachMent = new MimeBodyPart(); 
      FileDataSource dataSource = new FileDataSource(new File("file-sent.txt")); 
      attachMent.setDataHandler(new DataHandler(dataSource)); 
      attachMent.setFileName("file-sent.txt"); 
      attachMent.setDisposition(MimeBodyPart.ATTACHMENT); 
      Multipart multipart = new MimeMultipart(); 
      multipart.addBodyPart(body); 
      multipart.addBodyPart(attachMent); 
      msg.setContent(multipart); 
      Transport.send(msg); 
     } catch (AddressException ex) { 
      Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (MessagingException ex) { 
      Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

} 
20

Những người khác có câu trả lời hay ở trên nhưng tôi muốn thêm ghi chú về trải nghiệm của mình tại đây. Tôi thấy rằng khi sử dụng Gmail làm máy chủ SMTP đi cho ứng dụng web của tôi, Gmail chỉ cho phép tôi gửi ~ 10 thư trở lên trước khi trả lời phản hồi chống spam mà tôi phải thực hiện thủ công để bật lại quyền truy cập SMTP. Các email tôi gửi không phải là spam, nhưng là email "chào mừng" của trang web khi người dùng đăng ký với hệ thống của tôi. Vì vậy, YMMV và tôi sẽ không dựa vào Gmail cho một webapp sản xuất. Nếu bạn đang gửi email thay mặt người dùng, như ứng dụng dành cho máy tính để bàn được cài đặt (nơi người dùng nhập thông tin đăng nhập Gmail của riêng họ), bạn có thể không sao.

Ngoài ra, nếu bạn đang sử dụng Spring, đây là một cấu hình làm việc để sử dụng Gmail cho SMTP outbound:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
    <property name="defaultEncoding" value="UTF-8"/> 
    <property name="host" value="smtp.gmail.com"/> 
    <property name="port" value="465"/> 
    <property name="username" value="${mail.username}"/> 
    <property name="password" value="${mail.password}"/> 
    <property name="javaMailProperties"> 
     <value> 
      mail.debug=true 
      mail.smtp.auth=true 
      mail.smtp.socketFactory.class=java.net.SocketFactory 
      mail.smtp.socketFactory.fallback=false 
     </value> 
    </property> 
</bean> 
+0

Cảm ơn Jason, ví dụ về cài đặt cấu hình và cảnh báo giới hạn thư đi. Tôi đã không bao giờ chạy vào giới hạn trước đây, nhưng tôi chắc rằng những người khác sẽ thấy rằng thông tin đó hữu ích. –

+0

Tôi muốn biết thêm về giới hạn spam đó ... Tôi phải gửi một vài email, tôi có nên chia chúng thành từng nhóm không? đợi một khoảng thời gian nhất định? Có ai biết chi tiết về những hạn chế của google mail không? – opensas

3
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar 
import javax.mail.*; 
import javax.mail.internet.*; 
import java.util.*; 

public class Mail 
{ 
    String d_email = "[email protected]", 
      d_password = "****", 
      d_host = "smtp.gmail.com", 
      d_port = "465", 
      m_to = "[email protected]", 
      m_subject = "Testing", 
      m_text = "Hey, this is the testing email using smtp.gmail.com."; 
    public static void main(String[] args) 
    { 
     String[] to={"[email protected]"}; 
     String[] cc={"[email protected]"}; 
     String[] bcc={"[email protected]"}; 
     //This is for google 
     Mail.sendMail("[email protected]", "password", "smtp.gmail.com", 
         "465", "true", "true", 
         true, "javax.net.ssl.SSLSocketFactory", "false", 
         to, cc, bcc, 
         "hi baba don't send virus mails..", 
         "This is my style...of reply..If u send virus mails.."); 
    } 

    public synchronized static boolean sendMail(
     String userName, String passWord, String host, 
     String port, String starttls, String auth, 
     boolean debug, String socketFactoryClass, String fallback, 
     String[] to, String[] cc, String[] bcc, 
     String subject, String text) 
    { 
     Properties props = new Properties(); 
     //Properties props=System.getProperties(); 
     props.put("mail.smtp.user", userName); 
     props.put("mail.smtp.host", host); 
     if(!"".equals(port)) 
      props.put("mail.smtp.port", port); 
     if(!"".equals(starttls)) 
      props.put("mail.smtp.starttls.enable",starttls); 
     props.put("mail.smtp.auth", auth); 
     if(debug) { 
      props.put("mail.smtp.debug", "true"); 
     } else { 
      props.put("mail.smtp.debug", "false");   
     } 
     if(!"".equals(port)) 
      props.put("mail.smtp.socketFactory.port", port); 
     if(!"".equals(socketFactoryClass)) 
      props.put("mail.smtp.socketFactory.class",socketFactoryClass); 
     if(!"".equals(fallback)) 
      props.put("mail.smtp.socketFactory.fallback", fallback); 

     try 
     { 
      Session session = Session.getDefaultInstance(props, null); 
      session.setDebug(debug); 
      MimeMessage msg = new MimeMessage(session); 
      msg.setText(text); 
      msg.setSubject(subject); 
      msg.setFrom(new InternetAddress("[email protected]")); 
      for(int i=0;i<to.length;i++) { 
       msg.addRecipient(Message.RecipientType.TO, 
           new InternetAddress(to[i])); 
      } 
      for(int i=0;i<cc.length;i++) { 
       msg.addRecipient(Message.RecipientType.CC, 
           new InternetAddress(cc[i])); 
      } 
      for(int i=0;i<bcc.length;i++) { 
       msg.addRecipient(Message.RecipientType.BCC, 
           new InternetAddress(bcc[i])); 
      } 
      msg.saveChanges(); 
      Transport transport = session.getTransport("smtp"); 
      transport.connect(host, userName, passWord); 
      transport.sendMessage(msg, msg.getAllRecipients()); 
      transport.close(); 
      return true; 
     } 
     catch (Exception mex) 
     { 
      mex.printStackTrace(); 
      return false; 
     } 
    } 

} 
+3

Trông giống như mã php với tôi ... – Jamol

5

mã hoàn chỉnh của tôi như sau đang hoạt động tốt:

package ripon.java.mail; 
import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 

public class SendEmail 
{ 
public static void main(String [] args) 
{  
    // Sender's email ID needs to be mentioned 
    String from = "[email protected]"; 
    String pass ="test123"; 
    // Recipient's email ID needs to be mentioned. 
    String to = "[email protected]"; 

    String host = "smtp.gmail.com"; 

    // Get system properties 
    Properties properties = System.getProperties(); 
    // Setup mail server 
    properties.put("mail.smtp.starttls.enable", "true"); 
    properties.put("mail.smtp.host", host); 
    properties.put("mail.smtp.user", from); 
    properties.put("mail.smtp.password", pass); 
    properties.put("mail.smtp.port", "587"); 
    properties.put("mail.smtp.auth", "true"); 

    // Get the default Session object. 
    Session session = Session.getDefaultInstance(properties); 

    try{ 
     // Create a default MimeMessage object. 
     MimeMessage message = new MimeMessage(session); 

     // Set From: header field of the header. 
     message.setFrom(new InternetAddress(from)); 

     // Set To: header field of the header. 
     message.addRecipient(Message.RecipientType.TO, 
           new InternetAddress(to)); 

     // Set Subject: header field 
     message.setSubject("This is the Subject Line!"); 

     // Now set the actual message 
     message.setText("This is actual message"); 

     // Send message 
     Transport transport = session.getTransport("smtp"); 
     transport.connect(host, from, pass); 
     transport.sendMessage(message, message.getAllRecipients()); 
     transport.close(); 
     System.out.println("Sent message successfully...."); 
    }catch (MessagingException mex) { 
     mex.printStackTrace(); 
    } 
} 
} 
+1

Bạn là con đường ở phía dưới nhưng tôi thích bạn nhất! Cảm ơn bạn mã tuyệt vời. – gmustudent

+0

cảm ơn gmustudent –

2

Các giải pháp mã được đăng có thể gây ra sự cố khi bạn cần thiết lập nhiều phiên SMTP bất kỳ nơi nào trong cùng một JVM.

Các JavaMail FAQ khuyến cáo sử dụng

Session.getInstance(properties); 

thay vì

Session.getDefaultInstance(properties); 

vì getDefault sẽ chỉ sử dụng các thuộc tính cho lần đầu tiên nó được gọi. Tất cả các lần sử dụng sau này của cá thể mặc định sẽ bỏ qua các thay đổi về tài sản.

Xem http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance

+0

điểm rất tốt – Alix

0

Hi thử mã này ....

package my.test.service; 

import java.util.Properties; 

import javax.mail.Authenticator; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Message; 
import javax.mail.Transport; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 

public class Sample { 
    public static void main(String args[]) { 
     final String SMTP_HOST = "smtp.gmail.com"; 
     final String SMTP_PORT = "587"; 
     final String GMAIL_USERNAME = "[email protected]"; 
     final String GMAIL_PASSWORD = "xxxxxxxxxx"; 

     System.out.println("Process Started"); 

     Properties prop = System.getProperties(); 
     prop.setProperty("mail.smtp.starttls.enable", "true"); 
     prop.setProperty("mail.smtp.host", SMTP_HOST); 
     prop.setProperty("mail.smtp.user", GMAIL_USERNAME); 
     prop.setProperty("mail.smtp.password", GMAIL_PASSWORD); 
     prop.setProperty("mail.smtp.port", SMTP_PORT); 
     prop.setProperty("mail.smtp.auth", "true"); 
     System.out.println("Props : " + prop); 

     Session session = Session.getInstance(prop, new Authenticator() { 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication(GMAIL_USERNAME, 
         GMAIL_PASSWORD); 
      } 
     }); 

     System.out.println("Got Session : " + session); 

     MimeMessage message = new MimeMessage(session); 
     try { 
      System.out.println("before sending"); 
      message.setFrom(new InternetAddress(GMAIL_USERNAME)); 
      message.addRecipients(Message.RecipientType.TO, 
        InternetAddress.parse(GMAIL_USERNAME)); 
      message.setSubject("My First Email Attempt from Java"); 
      message.setText("Hi, This mail came from Java Application."); 
      message.setRecipients(Message.RecipientType.TO, 
        InternetAddress.parse(GMAIL_USERNAME)); 
      Transport transport = session.getTransport("smtp"); 
      System.out.println("Got Transport" + transport); 
      transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD); 
      transport.sendMessage(message, message.getAllRecipients()); 
      System.out.println("message Object : " + message); 
      System.out.println("Email Sent Successfully"); 
     } catch (AddressException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (MessagingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 
3

Các yêu cầu tối thiểu:

import java.util.Properties; 

import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 

public class MessageSender { 

    public static void sendHardCoded() throws AddressException, MessagingException { 
     String to = "[email protected]"; 
     final String from = "[email protected]"; 

     Properties properties = new Properties(); 
     properties.put("mail.smtp.starttls.enable", "true"); 
     properties.put("mail.smtp.auth", "true"); 
     properties.put("mail.smtp.host", "smtp.gmail.com"); 
     properties.put("mail.smtp.port", "587"); 

     Session session = Session.getInstance(properties, 
       new javax.mail.Authenticator() { 
        protected PasswordAuthentication getPasswordAuthentication() { 
         return new PasswordAuthentication(from, "BeNice"); 
        } 
       }); 

     MimeMessage message = new MimeMessage(session); 
     message.setFrom(new InternetAddress(from)); 
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
     message.setSubject("Hello"); 
     message.setText("What's up?"); 

     Transport.send(message); 
    } 

} 
+1

@ AlikElizin-kilaka Tôi đã cố gắng sử dụng id gmail cho cả người gửi và người nhận, thấy rằng bạn cũng cần đặt cờ Cho phép ứng dụng kém an toàn thành BẬT trong cài đặt tài khoản google của bạn, vì bạn truy cập hồ sơ gmail của bạn theo cách ít an toàn hơn. Sau đó, chỉ bạn mới có thể thấy email được gửi từ máy khách Java. Nếu không, bạn sẽ nhận được javax.mail.AuthenticationFailedException. – kunal

0

Dưới đây là một lớp dễ sử dụng cho việc gửi email với Gmail. Bạn cần có thư viện JavaMailadded to your build path hoặc chỉ sử dụng Maven.

import java.util.Properties; 

import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.mail.BodyPart; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Multipart; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 

public class GmailSender 
{ 
    private static String protocol = "smtp"; 

    private String username; 
    private String password; 

    private Session session; 
    private Message message; 
    private Multipart multipart; 

    public GmailSender() 
    { 
     this.multipart = new MimeMultipart(); 
    } 

    public void setSender(String username, String password) 
    { 
     this.username = username; 
     this.password = password; 

     this.session = getSession(); 
     this.message = new MimeMessage(session); 
    } 

    public void addRecipient(String recipient) throws AddressException, MessagingException 
    { 
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); 
    } 

    public void setSubject(String subject) throws MessagingException 
    { 
     message.setSubject(subject); 
    } 

    public void setBody(String body) throws MessagingException 
    { 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     messageBodyPart.setText(body); 
     multipart.addBodyPart(messageBodyPart); 

     message.setContent(multipart); 
    } 

    public void send() throws MessagingException 
    { 
     Transport transport = session.getTransport(protocol); 
     transport.connect(username, password); 
     transport.sendMessage(message, message.getAllRecipients()); 

     transport.close(); 
    } 

    public void addAttachment(String filePath) throws MessagingException 
    { 
     BodyPart messageBodyPart = getFileBodyPart(filePath); 
     multipart.addBodyPart(messageBodyPart); 

     message.setContent(multipart); 
    } 

    private BodyPart getFileBodyPart(String filePath) throws MessagingException 
    { 
     BodyPart messageBodyPart = new MimeBodyPart(); 
     DataSource dataSource = new FileDataSource(filePath); 
     messageBodyPart.setDataHandler(new DataHandler(dataSource)); 
     messageBodyPart.setFileName(filePath); 

     return messageBodyPart; 
    } 

    private Session getSession() 
    { 
     Properties properties = getMailServerProperties(); 
     Session session = Session.getDefaultInstance(properties); 

     return session; 
    } 

    private Properties getMailServerProperties() 
    { 
     Properties properties = System.getProperties(); 
     properties.put("mail.smtp.starttls.enable", "true"); 
     properties.put("mail.smtp.host", protocol + ".gmail.com"); 
     properties.put("mail.smtp.user", username); 
     properties.put("mail.smtp.password", password); 
     properties.put("mail.smtp.port", "587"); 
     properties.put("mail.smtp.auth", "true"); 

     return properties; 
    } 
} 

Ví dụ sử dụng:

GmailSender sender = new GmailSender(); 
sender.setSender("[email protected]", "mypassword"); 
sender.addRecipient("[email protected]"); 
sender.setSubject("The subject"); 
sender.setBody("The body"); 
sender.addAttachment("TestFile.txt"); 
sender.send(); 
0

Nếu bạn muốn sử dụng Outlook với Javamail API sau đó sử dụng

smtp-mail.outlook.com 

như một loạt cho mã hơn và đầy đủ làm việc Check out this answer.

+1

Trong khi liên kết này có thể trả lời câu hỏi, tốt hơn nên bao gồm các phần thiết yếu của câu trả lời ở đây và cung cấp liên kết để tham khảo. Câu trả lời chỉ liên kết có thể trở thành không hợp lệ nếu trang được liên kết thay đổi. - [Từ đánh giá] (/ review/low-quality-posts/14714106) – Sid

+0

Tôi đã đăng phần thiết yếu ở đây. Tìm mã duy nhất cần thiết ở đây là tên máy chủ có trong câu trả lời –

+0

Lưu ý. Và hoàn nguyên. – Sid

Các vấn đề liên quan