JavaMail發送簡單郵件代碼
package cn.jmail.test;import java.util.Properties;
import javax.mail.; import javax.mail.internet.;
public class FirstMail { /**
* 發送簡單郵件方法 * @param host 發送郵件服務器的IP * @param from 發送人地址 * @param to 接收人地址 * @param subject 郵件主題 * @param text 內容 * @param senderUsername 發送人的賬戶 * @param senderPassword 發送人的密碼 * mail.smtp.auth 是否需要身份驗證 一般都是需要的 */ public static void sendMail(String host, String from, String to, String subject, String text, final String senderUsername, final String senderPassword){ Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(senderUsername, senderPassword); } }); 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); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public static void main(String[] args) { String host = "smtp.163.com"; String from = "xxxxxx@163.com"; String to = "xxxxxxxx@qq.com"; String subject = "Hello, this is a test email."; String text = "Hello,LiLei."; String senderUsername = "xxxxxx@163.com"; String senderPassword = "xxxxxx"; FirstMail.sendMail(host, from, to, subject, text, senderUsername, senderPassword); }
}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!