java實現基於SMTP發送郵件的方法_java

來源:互聯網
上載者:User

本文執行個體講述了java實現基於SMTP發送郵件的方法。分享給大家供大家參考。具體實現方法如下:

import java.util.Date;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import org.apache.log4j.Logger;public class MailUtil { private static Logger logger = Logger.getLogger(MailUtil.class); /**  * 發送郵件  *   * @param smtp  *   SMTP伺服器  * @param user  *   使用者名稱  * @param password  *   密碼  * @param subject  *   標題  * @param content  *   郵件內容  * @param from  *   寄件者郵箱  * @param to  *   收件者郵箱  */ public static void send(String smtp, final String user,   final String password, String subject, String content, String from,   String to) {  try {   Properties props = new Properties();   props.put("mail.smtp.host", smtp);   props.put("mail.smtp.auth", "true");   Session ssn = Session.getInstance(props, new Authenticator() {    @Override    protected PasswordAuthentication getPasswordAuthentication() {     return new PasswordAuthentication(user, password);    }   });   MimeMessage message = new MimeMessage(ssn);   //由郵件會話建立一個訊息對象    InternetAddress fromAddress = new InternetAddress(from);   //寄件者的郵件地址    message.setFrom(fromAddress);   //設定寄件者    InternetAddress toAddress = new InternetAddress(to);   //收件者的郵件地址    message.addRecipient(Message.RecipientType.TO, toAddress);   //設定收件者   message.setSubject(subject);   //設定標題   message.setText(content);   //設定內容   message.setSentDate(new Date());   //設定發信時間    Transport transport = ssn.getTransport("smtp");   transport.connect(smtp, user, password);   transport.sendMessage(message, message     .getRecipients(Message.RecipientType.TO));   // transport.send(message);   transport.close();   logger.info("郵件發送成功");  } catch (Exception e) {   logger.warn("郵件發送失敗", e);  } }}

希望本文所述對大家的java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.