Rumah >Java >javaTutorial >Bagaimanakah Aplikasi Java Boleh Menghantar E-mel melalui Gmail, Yahoo atau Hotmail?
Soalan:
Bolehkah aplikasi Java menggunakan akaun e-mel seperti GMail, Yahoo, atau Hotmail untuk menghantar e-mel? Bagaimanakah ini boleh dicapai?
Jawapan:
Langkah 1: Import JavaMail API
Sebelum meneruskan, pastikan anda telah memuat turun dan menambah balang API JavaMail yang diperlukan pada anda classpath.
Langkah 2: Konfigurasi GMail
Coretan kod Java berikut menunjukkan penghantaran e-mel menggunakan akaun GMail:
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (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 { // Set email properties message.setFrom(new InternetAddress(from)); // Create InternetAddress array for recipients InternetAddress[] toAddress = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { toAddress[i] = new InternetAddress(to[i]); } // Set recipients for (InternetAddress addr : toAddress) { message.addRecipient(Message.RecipientType.TO, addr); } // Set subject and body message.setSubject(subject); message.setText(body); // Establish connection and send email 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(); } } }
Nota: Gantikan USER_NAME, KATA LALUAN, PENERIMA, subjek, dan pembolehubah badan dengan nilai yang sesuai.
Pertimbangan Tambahan:
Atas ialah kandungan terperinci Bagaimanakah Aplikasi Java Boleh Menghantar E-mel melalui Gmail, Yahoo atau Hotmail?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!