JAVA发送邮件最全示例

发送邮件是我们在程序开发中很常见的功能,比如注册通知、找回密码等,在网上也有很多关于JAVA发送邮件的示例,但多数都是只介绍了其中的一部分,今天为大家提供一些JAVA发送各种形式邮件的示例,供大家学习参考。

JAVA Mail

JAVA Mail是很常用的用于发送邮件的包,我们可以从这里获取,或者在maven中添加如下配置:

<dependency>
   <groupId>com.sun.mail</groupId>
   <artifactId>javax.mail</artifactId>
   <version>1.5.5</version>
</dependency>
 
  • 1
  • 2
  • 3
  • 4
  • 5

如果使用junit测试还需要添加:

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.8.2</version>
</dependency>
 
  • 1
  • 2
  • 3
  • 4
  • 5

示例代码如下:

package com.gujin.mail;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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;
import javax.mail.internet.MimeUtility;

public class MailSenderTest
{
   private String host = "smtp.126.com";
   private String port = "25";
   private String userName = "";
   private String password = "";
   private String to = "";

   /**
    * 发送文本邮件
    * 
    * @throws Exception
    */
   public void sendTextMail() throws Exception
   {
      Properties pro = System.getProperties();
      pro.put("mail.smtp.host", host);
      pro.put("mail.smtp.port", port);
      pro.put("mail.smtp.auth", "true");

      // 根据邮件会话属性和密码验证器构造一个发送邮件的session
      Session sendMailSession = Session.getDefaultInstance(pro,
            new Authenticator()
            {
               @Override
               protected PasswordAuthentication getPasswordAuthentication()
               {
                  return new PasswordAuthentication(userName, password);
               }
            });
      // 根据session创建一个邮件消息
      Message mailMessage = new MimeMessage(sendMailSession);
      // 设置邮件消息的发送者
      mailMessage.setFrom(new InternetAddress(userName));
      // 创建邮件的接收者地址,并设置到邮件消息中
      mailMessage.setRecipient(Message.RecipientType.TO,
            new InternetAddress(to));
      // 设置邮件消息的主题
      mailMessage.setSubject("Test Email");
      // 设置邮件消息发送的时间
      mailMessage.setSentDate(new Date());
      // 设置邮件消息的主要内容
      mailMessage.setText("this is a test Text mail");
      // 发送邮件
      Transport.send(mailMessage);
   }

   /**
    * 发送Html邮件
    * 
    * @throws Exception
    */
   public void sendHtmlMail() throws Exception
   {
      Properties pro = System.getProperties();
      pro.put("mail.smtp.host", host);
      pro.put("mail.smtp.port", port);
      pro.put("mail.smtp.auth", "true");

      // 根据邮件会话属性和密码验证器构造一个发送邮件的session
      Session sendMailSession = Session.getDefaultInstance(pro,
            new Authenticator()
            {
               @Override
               protected PasswordAuthentication getPasswordAuthentication()
               {
                  return new PasswordAuthentication(userName, password);
               }
            });
      // 根据session创建一个邮件消息
      Message mailMessage = new MimeMessage(sendMailSession);
      // 设置邮件消息的发送者
      mailMessage.setFrom(new InternetAddress(userName));
      // 创建邮件的接收者地址,并设置到邮件消息中
      mailMessage.setRecipient(Message.RecipientType.TO,
            new InternetAddress(to));
      // 设置邮件消息的主题
      mailMessage.setSubject("Test Email");
      // 设置邮件消息发送的时间
      mailMessage.setSentDate(new Date());

      // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
      Multipart mainPart = new MimeMultipart();
      // 创建一个包含HTML内容的MimeBodyPart
      BodyPart html = new MimeBodyPart();
      // 设置HTML内容
      html.setContent(
            "<html><body><img src='http://avatar.youkuaiyun.com/A/C/A/1_jianggujin.jpg'/><div>this is a HTML email.</div></body></html>",
            "text/html; charset=utf-8");
      mainPart.addBodyPart(html);
      // 将MiniMultipart对象设置为邮件内容
      mailMessage.setContent(mainPart);
      // 发送邮件
      Transport.send(mailMessage);
   }

   /**
    * 发送内嵌图片邮件
    * 
    * @throws Exception
    */
   public void sendImageMail() throws Exception
   {
      Properties pro = System.getProperties();
      pro.put("mail.smtp.host", host);
      pro.put("mail.smtp.port", port);
      pro.put("mail.smtp.auth", "true");

      // 根据邮件会话属性和密码验证器构造一个发送邮件的session
      Session sendMailSession = Session.getDefaultInstance(pro,
            new Authenticator()
            {
               @Override
               protected PasswordAuthentication getPasswordAuthentication()
               {
                  return new PasswordAuthentication(userName, password);
               }
            });
      // 根据session创建一个邮件消息
      Message mailMessage = new MimeMessage(sendMailSession);
      // 设置邮件消息的发送者
      mailMessage.setFrom(new InternetAddress(userName));
      // 创建邮件的接收者地址,并设置到邮件消息中
      mailMessage.setRecipient(Message.RecipientType.TO,
            new InternetAddress(to));
      // 设置邮件消息的主题
      mailMessage.setSubject("Test Email");
      // 设置邮件消息发送的时间
      mailMessage.setSentDate(new Date());

      MimeMultipart multipart = new MimeMultipart("related");

      BodyPart messageBodyPart = new MimeBodyPart();
      String htmlText = "<html><body><img src='cid:image'/><div>this is a HTML email.</div></body></html>";
      messageBodyPart.setContent(htmlText, "text/html; charset=utf-8");
      multipart.addBodyPart(messageBodyPart);

      MimeBodyPart imageBodyPart = new MimeBodyPart();
      DataSource fds = new FileDataSource("1_jianggujin.jpg");
      imageBodyPart.setDataHandler(new DataHandler(fds));
      imageBodyPart.setContentID("image");
      multipart.addBodyPart(imageBodyPart);

      mailMessage.setContent(multipart);
      // 发送邮件
      Transport.send(mailMessage);
   }

   /**
    * 发送附件邮件
    * 
    * @throws Exception
    */
   public void sendAttachmentMail() throws Exception
   {
      Properties pro = System.getProperties();
      pro.put("mail.smtp.host", host);
      pro.put("mail.smtp.port", port);
      pro.put("mail.smtp.auth", "true");

      // 根据邮件会话属性和密码验证器构造一个发送邮件的session
      Session sendMailSession = Session.getDefaultInstance(pro,
            new Authenticator()
            {
               @Override
               protected PasswordAuthentication getPasswordAuthentication()
               {
                  return new PasswordAuthentication(userName, password);
               }
            });
      // 根据session创建一个邮件消息
      Message mailMessage = new MimeMessage(sendMailSession);
      // 设置邮件消息的发送者
      mailMessage.setFrom(new InternetAddress(userName));
      // 创建邮件的接收者地址,并设置到邮件消息中
      mailMessage.setRecipient(Message.RecipientType.TO,
            new InternetAddress(to));
      // 设置邮件消息的主题
      mailMessage.setSubject("Test Email");
      // 设置邮件消息发送的时间
      mailMessage.setSentDate(new Date());

      MimeMultipart multipart = new MimeMultipart("mixed");

      BodyPart messageBodyPart = new MimeBodyPart();
      String htmlText = "<html><body><div>this is a Attachment email.this email has a attachment!</div></body></html>";
      messageBodyPart.setContent(htmlText, "text/html; charset=utf-8");
      multipart.addBodyPart(messageBodyPart);

      MimeBodyPart imageBodyPart = new MimeBodyPart();
      File imageFile = new File("1_jianggujin.jpg");
      DataSource fds = new FileDataSource(imageFile);
      imageBodyPart.setDataHandler(new DataHandler(fds));
      imageBodyPart.setFileName(MimeUtility.encodeWord(imageFile.getName()));
      multipart.addBodyPart(imageBodyPart);

      mailMessage.setContent(multipart);
      // 发送邮件
      Transport.send(mailMessage);
   }

   /**
    * 发送内嵌图片和附件邮件
    * 
    * @throws Exception
    */
   public void sendImageAndAttachmentMail() throws Exception
   {
      Properties pro = System.getProperties();
      pro.put("mail.smtp.host", host);
      pro.put("mail.smtp.port", port);
      pro.put("mail.smtp.auth", "true");

      // 根据邮件会话属性和密码验证器构造一个发送邮件的session
      Session sendMailSession = Session.getDefaultInstance(pro,
            new Authenticator()
            {
               @Override
               protected PasswordAuthentication getPasswordAuthentication()
               {
                  return new PasswordAuthentication(userName, password);
               }
            });
      // 根据session创建一个邮件消息
      Message mailMessage = new MimeMessage(sendMailSession);
      // 设置邮件消息的发送者
      mailMessage.setFrom(new InternetAddress(userName));
      // 创建邮件的接收者地址,并设置到邮件消息中
      mailMessage.setRecipient(Message.RecipientType.TO,
            new InternetAddress(to));
      // 设置邮件消息的主题
      mailMessage.setSubject("Test Email");
      // 设置邮件消息发送的时间
      mailMessage.setSentDate(new Date());

      // 正文
      MimeBodyPart text = new MimeBodyPart();
      text.setContent("我的头像:<img src='cid:headImg'>",
            "text/html;charset=UTF-8");

      // 正文图片
      MimeBodyPart image = new MimeBodyPart();
      image.setDataHandler(
            new DataHandler(new FileDataSource("1_jianggujin.jpg")));
      image.setContentID("headImg");

      // 附件
      MimeBodyPart attach = new MimeBodyPart();
      DataHandler dh = new DataHandler(new FileDataSource("1_jianggujin.jpg"));
      attach.setDataHandler(dh);
      attach.setFileName(MimeUtility.encodeWord(dh.getName()));

      // 描述关系:正文和图片
      MimeMultipart mp1 = new MimeMultipart();
      mp1.addBodyPart(text);
      mp1.addBodyPart(image);
      mp1.setSubType("related");

      // 正文
      MimeBodyPart content = new MimeBodyPart();
      content.setContent(mp1);

      MimeMultipart multipart = new MimeMultipart("mixed");
      multipart.addBodyPart(content);
      multipart.addBodyPart(attach);

      mailMessage.setContent(multipart);
      // 发送邮件
      Transport.send(mailMessage);
   }
}
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293

commons-email

使用JAVA Mail我们可以完成邮件的发送,但是我们可以发现实现过程略显复杂,比较繁琐,所以我们可以借助commons-email简化发送邮件的过程,commons-email可以从这里下载,或在maven中添加如下配置:

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-email</artifactId>
   <version>1.4</version>
</dependency>
 
  • 1
  • 2
  • 3
  • 4
  • 5

示例代码:

package com.gujin.mail;

import java.io.File;
import java.util.Date;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

public class CommonsEmailTest
{
   private String host = "smtp.126.com";
   private int port = 25;
   private String userName = "";
   private String password = "";
   private String to = "";

   /**
    * 发送文本邮件
    * 
    * @throws Exception
    */
   public void sendTextMail() throws Exception
   {
      SimpleEmail mail = new SimpleEmail();
      // 设置邮箱服务器信息
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 设置密码验证器
      mail.setAuthentication(userName, password);
      // 设置邮件发送者
      mail.setFrom(userName);
      // 设置邮件接收者
      mail.addTo(to);
      // 设置邮件编码
      mail.setCharset("UTF-8");
      // 设置邮件主题
      mail.setSubject("Test Email");
      // 设置邮件内容
      mail.setMsg("this is a test Text mail");
      // 设置邮件发送时间
      mail.setSentDate(new Date());
      // 发送邮件
      mail.send();
   }

   /**
    * 发送Html邮件
    * 
    * @throws Exception
    */
   public void sendHtmlMail() throws Exception
   {
      HtmlEmail mail = new HtmlEmail();
      // 设置邮箱服务器信息
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 设置密码验证器
      mail.setAuthentication(userName, password);
      // 设置邮件发送者
      mail.setFrom(userName);
      // 设置邮件接收者
      mail.addTo(to);
      // 设置邮件编码
      mail.setCharset("UTF-8");
      // 设置邮件主题
      mail.setSubject("Test Email");
      // 设置邮件内容
      mail.setHtmlMsg(
            "<html><body><img src='http://avatar.youkuaiyun.com/A/C/A/1_jianggujin.jpg'/><div>this is a HTML email.</div></body></html>");
      // 设置邮件发送时间
      mail.setSentDate(new Date());
      // 发送邮件
      mail.send();
   }

   /**
    * 发送内嵌图片邮件
    * 
    * @throws Exception
    */
   public void sendImageMail() throws Exception
   {
      HtmlEmail mail = new HtmlEmail();
      // 设置邮箱服务器信息
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 设置密码验证器
      mail.setAuthentication(userName, password);
      // 设置邮件发送者
      mail.setFrom(userName);
      // 设置邮件接收者
      mail.addTo(to);
      // 设置邮件编码
      mail.setCharset("UTF-8");
      // 设置邮件主题
      mail.setSubject("Test Email");
      mail.embed(new File("1_jianggujin.jpg"), "image");
      // 设置邮件内容
      String htmlText = "<html><body><img src='cid:image'/><div>this is a HTML email.</div></body></html>";
      mail.setHtmlMsg(htmlText);
      // 设置邮件发送时间
      mail.setSentDate(new Date());
      // 发送邮件
      mail.send();
   }

   /**
    * 发送附件邮件
    * 
    * @throws Exception
    */
   public void sendAttachmentMail() throws Exception
   {
      MultiPartEmail mail = new MultiPartEmail();
      // 设置邮箱服务器信息
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 设置密码验证器
      mail.setAuthentication(userName, password);
      // 设置邮件发送者
      mail.setFrom(userName);
      // 设置邮件接收者
      mail.addTo(to);
      // 设置邮件编码
      mail.setCharset("UTF-8");
      // 设置邮件主题
      mail.setSubject("Test Email");

      mail.setMsg("this is a Attachment email.this email has a attachment!");
      // 创建附件
      EmailAttachment attachment = new EmailAttachment();
      attachment.setPath("1_jianggujin.jpg");
      attachment.setDisposition(EmailAttachment.ATTACHMENT);
      attachment.setName("1_jianggujin.jpg");
      mail.attach(attachment);

      // 设置邮件发送时间
      mail.setSentDate(new Date());
      // 发送邮件
      mail.send();
   }

   /**
    * 发送内嵌图片和附件邮件
    * 
    * @throws Exception
    */
   public void sendImageAndAttachmentMail() throws Exception
   {
      HtmlEmail mail = new HtmlEmail();
      // 设置邮箱服务器信息
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 设置密码验证器
      mail.setAuthentication(userName, password);
      // 设置邮件发送者
      mail.setFrom(userName);
      // 设置邮件接收者
      mail.addTo(to);
      // 设置邮件编码
      mail.setCharset("UTF-8");
      // 设置邮件主题
      mail.setSubject("Test Email");
      mail.embed(new File("1_jianggujin.jpg"), "image");
      // 设置邮件内容
      String htmlText = "<html><body><img src='cid:image'/><div>this is a HTML email.</div></body></html>";
      mail.setHtmlMsg(htmlText);
      // 创建附件
      EmailAttachment attachment = new EmailAttachment();
      attachment.setPath("1_jianggujin.jpg");
      attachment.setDisposition(EmailAttachment.ATTACHMENT);
      attachment.setName("1_jianggujin.jpg");
      mail.attach(attachment);
      // 设置邮件发送时间
      mail.setSentDate(new Date());
      // 发送邮件
      mail.send();
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值