JavaMail邮件发送传输相关代码案例解析

目录

一、向服务器账号发送一封有文本内容的普通信件

①需要先创建Session会话建立连接,此处需要账号和授权密码等数据,所以为了使代码简洁可以先创建一个工具类,写一个方法来完成此操作......(此处工具类且命名为JavaMailutil,具体代码如下:)

②创建邮件的对象

③发送操作

二、向服务器账号发送一封即具有文本内容,又有一附件的信件,同时向另一个或多个账号进行抄送

①建立Session会话(运用工具类快速完成)

②创建邮件对象

③发送邮件


一、向服务器账号发送一封有文本内容的普通信件

【例:文件标题为“雾已散声声慢”,发送的文本内容:“无人问津的我!”】

①需要先创建Session会话建立连接,此处需要账号和授权密码等数据,所以为了使代码简洁可以先创建一个工具类,写一个方法来完成此操作......(此处工具类且命名为JavaMailutil,具体代码如下:)
package HTTP;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

public final class JavaMailutil {

 //将该方法设为私有方法
 private JavaMailutil() {
	 
 }
 
 
 public static Session createSession() {
	 String userName = "123456789@163.com";//邮箱发送账号(自己的账号)
     String passWord = "AJLFPVMRWPCJVRTS";//账号授权密码
     
     
     Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.163.com");//SMTP主机名
     props.put("mail.smtp.port", "25");//主机端口号
     props.put("mail.smtp.auth", "true");//是否需要用户认证
     props.put("mail.smtp.starttls.enable", "true");//启用TLS加密
     
     //创建session会话
     //1.smtp服务器连接参数
     //2.账号和密码的授权对象
     Session session = Session.getInstance(props, new Authenticator() {
    	 @Override
    	protected PasswordAuthentication getPasswordAuthentication() {
    		return new PasswordAuthentication(userName,passWord);//验证用户名和密码
    	}
	});
     //session.setDebug(true);
     return session;
}
}

  在写完工具类方法后我就可以用该方法快捷建立Session会话,代码如下:

Session session = JavaMailutil.createSession();
②创建邮件的对象

1.获取文本标题

2.获取文本内容

3.获取发送邮箱

4.获取接邮邮箱(此处只向一个邮箱发送,所以运用RecipientType.TO)


代码如下:

        //2.创建邮件对象
		MimeMessage message = new MimeMessage(session);
		message.setSubject("雾已散声声慢");
		message.setText("无人问津的我!");
		message.setFrom(new InternetAddress("123454321@163.com"));
		message.setRecipient(RecipientType.TO, new InternetAddress("123456789@qq.com"));
③发送操作
Transport.send(message);

【注:需要用try catch处理异常,所以所有的代码都在try catch中】

二、向服务器账号发送一封即具有文本内容,又有一附件的信件,同时向另一个或多个账号进行抄送

【注:内容不变,只多一张照片】

①建立Session会话(运用工具类快速完成
Session session = JavaMailutil.createSession();
②创建邮件对象

【注:要在电子邮件中携带附件,我们就不能直接调用message.setText()方法,而是要构造一个Multipart对象】

//2.创建邮件对象
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress("123454321@163.com"));
		message.setRecipient(RecipientType.TO, new InternetAddress("123456789@qq.com"));
		message.setRecipients(RecipientType.CC, new InternetAddress[]{newInternetAddress("2273957338@qq.com")});//因为可多个所以用数组完成
        message.setSubject("雾已散声声慢");//文件标题
		

//邮件中包含正文,又包含文件
//一个Multipart对象可以添加若干个BodyPart,其中第一个BodyPart是文本,即邮件正文,后面的BodyPart是附件。BodyPart依靠setContent()决定添加的内容

	 	//正文
		BodyPart textpart = new MimeBodyPart();
		StringBuilder contentText = new StringBuilder();
		contentText.append("<h1>无人问津的我!</h1>");
		contentText.append("<img src=\"cid:ssm\"/>");//内容ID
		textpart.setContent(contentText.toString(), "text/html;charset = utf-8");//格式
		
		
		BodyPart imagepart = new MimeBodyPart();
		imagepart.setDataHandler(new DataHandler(new ByteArrayDataSource(Files.readAllBytes(Paths.get("F:\\XXXX.jpg")), "application/octet-stream")));
		
        //图片的内容ID
		imagepart.setHeader("content-ID", "ssm");
		

        //将正文+附件组装
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(textpart);
		multipart.addBodyPart(imagepart);
		
		message.setContent(multipart);

【注:抄送使用RecipientType.CC和数组完成】

③发送邮件
Transport.send(message);
System.out.println("发送成功。");//方便查看是否成功
发送邮件时,我们需要构造一个Message对象,然后调用Transport.send(Message)即可完成发送:绝大多数邮件服务器要求发送方地址和登录用户名必须一致,否则发送将失败。

By  Mr.GUGUGU

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
可以使用JavaMail实现批量发送邮件,主要步骤如下: 1. 配置邮件服务器信息,包括SMTP服务器地址、端口号、用户名和密码等。 2. 创建JavaMail会话对象,可以通过Session.getDefaultInstance()方法获取默认会话对象,也可以自己创建Session对象。 3. 创建邮件对象,包括发件人、收件人、主题、内容等。 4. 创建多个邮件对象,将它们添加到一个邮件列表中。 5. 创建邮件传输对象Transport,连接邮件服务器并发送邮件列表。 下面是一个简单的示例代码: ``` import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class MailSender { public static void main(String[] args) throws Exception { String host = "smtp.example.com"; String username = "your_username"; String password = "your_password"; String from = "your_email@example.com"; String subject = "Test Email"; String body = "This is a test email."; Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); List<String> toList = new ArrayList<String>(); toList.add("recipient1@example.com"); toList.add("recipient2@example.com"); toList.add("recipient3@example.com"); List<Message> messageList = new ArrayList<Message>(); for (String to : toList) { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); messageList.add(message); } Transport transport = session.getTransport("smtp"); transport.connect(); for (Message message : messageList) { transport.sendMessage(message, message.getAllRecipients()); } transport.close(); } } ``` 在上面的示例代码中,我们将收件人地址保存在一个列表中,然后创建多个邮件对象,将它们添加到一个邮件列表中,最后使用Transport对象发送邮件列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值