問題:
Java 應用程式使用電子郵件帳號像GMail、Yahoo 或Hotmail 一樣傳送電子郵件?如何實現這一點?答案:
第1 步:匯入JavaMail API
在繼續之前,請確保您已下載所需的JavaMail API jar 並將其新增至您的第 2步驟:GMail 設定
以下Java 程式碼片段示範使用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(); } } }
注意:
將USER_NAME、PASSWORD、RECIPIENTWORDORD、和body變數替換為適當的其他注意事項:
以上是Java 應用程式如何透過 Gmail、Yahoo 或 Hotmail 發送電子郵件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!