2013-04-15 2 views
0

Недавно я сделал веб-приложение в Java netbeans, и я сделал регистрацию и систему входа в систему, можете ли вы рассказать мне, как отправить электронное письмо с помощью java, поэтому, когда пользователь зарегистрируется, он получит приветственное сообщение в его электронной почте. Мне просто нужен код для отправки электронной почты.Отправка электронной почты с использованием Java Netbeans

+0

Google JavaMail. –

+0

Возможный дубликат [Отправить письмо с помощью java] (http://stackoverflow.com/questions/3649014/send-email-using-java) –

ответ

0

От this question:

Следующий код работает очень хорошо с сервером Google SMTP. Вам необходимо указать свое имя пользователя и пароль Google. (Не забудьте скачать JavaMail API)

import com.sun.mail.smtp.SMTPTransport; 
import java.security.Security; 
import java.util.Date; 
import java.util.Properties; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Session; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 

public class GoogleMail { 
    private GoogleMail() { 
    } 

    /** 
    * Send email using GMail SMTP server. 
    * 
    * @param username GMail username 
    * @param password GMail password 
    * @param recipientEmail TO recipient 
    * @param title title of the message 
    * @param message message to be sent 
    * @throws AddressException if the email address parse failed 
    * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage 
    */ 
    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException { 
     GoogleMail.Send(username, password, recipientEmail, "", title, message); 
    } 

    /** 
    * Send email using GMail SMTP server. 
    * 
    * @param username GMail username 
    * @param password GMail password 
    * @param recipientEmail TO recipient 
    * @param ccEmail CC recipient. Can be empty if there is no CC recipient 
    * @param title title of the message 
    * @param message message to be sent 
    * @throws AddressException if the email address parse failed 
    * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage 
    */ 
    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException { 
     Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 
     final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 

     // Get a Properties object 
     Properties props = System.getProperties(); 
     props.setProperty("mail.smtps.host", "smtp.gmail.com"); 
     props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); 
     props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
     props.setProperty("mail.smtp.port", "465"); 
     props.setProperty("mail.smtp.socketFactory.port", "465"); 
     props.setProperty("mail.smtps.auth", "true"); 

     /* 
     If set to false, the QUIT command is sent and the connection is immediately closed. If set 
     to true (the default), causes the transport to wait for the response to the QUIT command. 

     ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html 
       http://forum.java.sun.com/thread.jspa?threadID=5205249 
       smtpsend.java - demo program from javamail 
     */ 
     props.put("mail.smtps.quitwait", "false"); 

     Session session = Session.getInstance(props, null); 

     // -- Create a new message -- 
     final MimeMessage msg = new MimeMessage(session); 

     // -- Set the FROM and TO fields -- 
     msg.setFrom(new InternetAddress(username + "@gmail.com")); 
     msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); 

     if (ccEmail.length() > 0) { 
      msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); 
     } 

     msg.setSubject(title); 
     msg.setText(message, "utf-8"); 
     msg.setSentDate(new Date()); 

     SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); 

     t.connect("smtp.gmail.com", username, password); 
     t.sendMessage(msg, msg.getAllRecipients());  
     t.close(); 
    } 
} 
+0

У меня ошибка в строке импорта (javax.mail не существует) – user2284478

+0

Вам необходимо загрузить [API JavaMail] (http://www.oracle.com/technetwork/java/javamail/index.html) и поместить соответствующие файлы jar в свой путь к классам. – syb0rg

1

списаны из here:

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

public class SendMailUsingAuthentication 
{ 
    private static final String SMTP_HOST_NAME = "gemini.jvmhost.com"; //or simply "localhost" 
    private static final String SMTP_AUTH_USER = "[email protected]"; 
    private static final String SMTP_AUTH_PWD = "secret"; 
    private static final String emailMsgTxt  = "Body"; 
    private static final String emailSubjectTxt = "Subject"; 
    private static final String emailFromAddress = "[email protected]"; 

    // Add List of Email address to who email needs to be sent to 
    private static final String[] emailList = {"[email protected]"}; 

    public static void main(String args[]) throws Exception 
    { 
    SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication(); 
    smtpMailSender.postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress); 
    System.out.println("Sucessfully Sent mail to All Users"); 
    } 

    public void postMail(String recipients[ ], String subject, 
    String message , String from) throws MessagingException, AuthenticationFailedException 
    { 
    boolean debug = false; 

    //Set the host smtp address 
    Properties props = new Properties(); 
    props.put("mail.smtp.host", SMTP_HOST_NAME); 
    props.put("mail.smtp.auth", "true"); 
    Authenticator auth = new SMTPAuthenticator(); 
    Session session = Session.getDefaultInstance(props, auth); 

    session.setDebug(debug); 

    // create a message 
    Message msg = new MimeMessage(session); 

    // set the from and to address 
    InternetAddress addressFrom = new InternetAddress(from); 
    msg.setFrom(addressFrom); 

    InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
    for (int i = 0; i < recipients.length; i++) 
    { 
     addressTo[i] = new InternetAddress(recipients[i]); 
    } 
    msg.setRecipients(Message.RecipientType.TO, addressTo); 

    // Setting the Subject and Content Type 
    msg.setSubject(subject); 
    msg.setContent(message, "text/plain"); 
    Transport.send(msg); 
} 

private class SMTPAuthenticator extends javax.mail.Authenticator 
{ 
    public PasswordAuthentication getPasswordAuthentication() 
    { 
     String username = SMTP_AUTH_USER; 
     String password = SMTP_AUTH_PWD; 
     return new PasswordAuthentication(username, password); 
    } 
} 
} 

Если вам нужна дополнительная помощь, дайте мне знать, и я помогу.

+0

У меня ошибка в строке импорта (javax.mail не существует) – user2284478

+0

Добавьте javamail jar в свой путь к классам – hd1

+0

Где я могу найти этот файл jar? – user2284478

0

Здесь вы можете найти образец класса Java, предназначенный для отправки электронных писем с помощью учетной записи Google. Пожалуйста, следуйте следующим link

Он использует следующие свойства

Properties props = new Properties(); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.port", "587"); 
Смежные вопросы