1. 程式人生 > >應用java mail和阿里雲傳送郵件和上傳附件

應用java mail和阿里雲傳送郵件和上傳附件

package com.mail; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class SendMail { public static void main(String[] args) throws MessagingException, UnsupportedEncodingException { Properties prop=new Properties(); prop.put("mail.host","smtp.aliyun.com" ); prop.put("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", "true"); Session session=Session.getInstance(prop); session.setDebug(true); Transport ts=session.getTransport(); ts.connect("[email protected]", "123456"); //登入的賬戶名 和 密碼 Message msg=createSimpleMail(session); ts.sendMessage(msg, msg.getAllRecipients()); } public static MimeMessage createSimpleMail(Session session) throws AddressException,MessagingException, UnsupportedEncodingException{ MimeMessage mm=new MimeMessage(session); mm.setFrom(new InternetAddress("
[email protected]
")); //設定發件人 mm.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); //設定收件人 //mm.setRecipient(Message.RecipientType.CC, new InternetAddress("[email protected]")); //設定抄送人 mm.setSubject("清算清單!"); Multipart multipart = new MimeMultipart(); String mailBody = "請查收"; BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(mailBody, "text/html;charset=utf-8"); multipart.addBodyPart(bodyPart); BodyPart bodyPart1 = new MimeBodyPart(); FileDataSource fileDataSource = new FileDataSource("c:/投資(或清算)總表.xlsx"); bodyPart1.setDataHandler(new DataHandler(fileDataSource)); bodyPart1.setFileName(MimeUtility.encodeText(fileDataSource.getName())); multipart.addBodyPart(bodyPart1); mm.setContent(multipart); mm.saveChanges(); return mm; } }