2012-09-11 13 views
5

Chcę wysłać pocztę w moim programie java przez serwer smtp google, ale wydaje się, że utknął w wysyłaniu poczty. Czy ktoś może mi powiedzieć, dlaczego to jest?java mail gmail

jest to funkcja, aby wysłać mail:

 public void sendMail(){ 
      String from = "[email protected]"; 
    String to = "[email protected]"; 
    String subject = "Test"; 
    String message = "A test message"; 

    SendMail sendMail = new SendMail(from, to, subject, message); 
    sendMail.send(); 
} 

I to jest klasa

public class SendMail { 
private String from; 
private String to; 
private String subject; 
private String text; 

public SendMail(String from, String to, String subject, String text){ 
    this.from = from; 
    this.to = to; 
    this.subject = subject; 
    this.text = text; 
} 

public void send(){ 

    Properties props = new Properties(); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.auth", "true"); 
    props.setProperty("mail.smtp.port", "587"); 
    props.put("mail.smtp.starttls.enable", "true"); 
    Session session = Session.getDefaultInstance(props); 

    new javax.mail.Authenticator() { 
    protected PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication(from, "MyPasswordGoesHere"); 
    } 
     }; 

    try { 
    MimeMessage message = new MimeMessage(session); 
    message.setFrom(new InternetAddress(from)); 
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
    message.setSubject(subject); 
    message.setText(text); 

    Transport.send(message); 
    System.out.println("message sent successfully"); 
    } catch (MessagingException e) { 
    throw new RuntimeException(e); 
    } 
     } 
     } 

Z góry dzięki!

+0

¿Czy powoduje błąd lub kończy się bez narzekania? Ustaw debugowanie na serwerze SMTP, aby zobaczyć, co robi klient. – Alfabravo

+0

sprawdź to, może pomóc ... http://www.javabeat.net/2007/10/sending-mail-from-java/ – NoNaMe

+0

@ sf shah użyłem tego jako przykładu i to nie kończy tego po prostu zawiesza się w "Transport.send (message); line – Nick

Odpowiedz

0

W my blog post, starałem się przykładem wysyłania wiadomości e-mail z Java na serwerze SMTP Gmaila. Tutaj są 2 przykładowe kody. Jeden z nich używa interfejsu Java Mail API, a drugi wykorzystuje bibliotekę poczty Apache Commons.

Powiązane problemy