- import java.util.List;
- import java.util.Map;
- 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.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- public class MailUtil {
- public static void sendMail(Map<String,String> mailInstallMap,String subject, String text,List<String> bccs) throws Exception
- {
- String mailhost=mailInstallMap.get("mailhost").trim();//邮箱服务器
- String port= mailInstallMap.get("port").trim();//邮箱服务器端口
- String from= mailInstallMap.get("from").trim();//发件人
-
-
- String file=null;//附件
-
- final String password= mailInstallMap.get("password");//密码
- final String user= mailInstallMap.get("user").trim();//用户名
-
-
-
-
- Properties props = new Properties();
-
- props.put("mail.smtp.host", mailhost);
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.port", port);
-
- Session session = Session.getDefaultInstance(props,new Authenticator() {
-
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user, password);
- }
-
- });
-
- session.setDebug(false);
- //构建邮件内容
-
- Message msg = new MimeMessage(session);
-
- msg.setFrom(new InternetAddress(from));
-
- for(String bccT:bccs )
- {
- String bcc=bccT.trim();
- msg.addRecipient(Message.RecipientType.BCC,
- new InternetAddress(bcc));
- }
-
- msg.setSubject(subject);
- if (file != null) {
-
- MimeBodyPart mbp1 = new MimeBodyPart();
- mbp1.setText(text);
- MimeBodyPart mbp2 = new MimeBodyPart();
- mbp2.attachFile(file);
- MimeMultipart mp = new MimeMultipart();
- mp.addBodyPart(mbp1);
- mp.addBodyPart(mbp2);
- msg.setContent(mp);
- } else {
-
- msg.setContent(text, "text/html;charset=UTF-8");
- }
- msg.saveChanges();
- // 发送邮件
- Transport.send(msg);
-
- // System.out.println("\nMail was sent successfully.");
-
- }
-
- }
复制代码
|
|