用java程式發送郵件,java程式發送郵件

來源:互聯網
上載者:User

用java程式發送郵件,java程式發送郵件

發送沒有附件的郵箱:

public void test2() throws Exception{
//1:聲明伺服器位址
Properties p = new Properties();
p.setProperty("mail.host","smtp.sohu.com");//指定伺服器,以搜狐郵箱為例
p.setProperty("mail.smtp.auth","true");//進行驗證
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxx","密碼");
}
};
//2:聲明Session
Session session = Session.getDefaultInstance(p,auth);
//設定為偵錯模式
session.setDebug(true);
//3:聲明資訊
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxxxxx@sohu.com"));
msg.setRecipient(RecipientType.TO,new InternetAddress("要發送的郵箱"));
msg.setSubject("標題,誰便");
msg.setContent("內容,自己寫","text/html;charset=UTF-8");
//發送
Transport.send(msg);
}

發送含有附件的郵件:

public void test3() throws Exception{
//1:聲明伺服器位址
Properties p = new Properties();
p.setProperty("mail.host","smtp.sohu.com");//指定伺服器,以搜狐為例
p.setProperty("mail.smtp.auth","true");//進行驗證
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxx","密碼");
}
};
//2:聲明Session
Session session = Session.getDefaultInstance(p,auth);
//設定為偵錯模式
session.setDebug(true);
//3:聲明資訊
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxxxxxx@sohu.com"));
msg.setRecipient(RecipientType.TO,new InternetAddress("要發送的郵箱"));
msg.setSubject("大家好1111");

//聲明Multibody
MimeMultipart multi = new MimeMultipart();
//添加一個附件
javax.mail.internet.MimeBodyPart part1 = new javax.mail.internet.MimeBodyPart();
part1.attachFile(new File("檔案的地址"));
part1.setFileName(MimeUtility.encodeText("要發送的檔案名稱及尾碼"));
multi.addBodyPart(part1);
javax.mail.internet.MimeBodyPart part2 = new javax.mail.internet.MimeBodyPart();
part2.setContent("你好這是內容<b>Hello</b>","text/html;charset=UTF-8");

multi.addBodyPart(part2);

msg.setContent(multi);


Transport.send(msg);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.