用JavaMail发送邮件

本文提供了一个使用JavaMail API发送电子邮件的示例代码。该示例展示了如何配置SMTP服务器并利用mail.jar和activation.jar库来发送邮件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录一段用过的代码,方便以后备查。
需要用到的jar包为:mail.jar、activation.jar
可到如下位置下载:
http://java.sun.com/products/javamail/downloads/index.html
http://java.sun.com/products/javabeans/jaf/downloads/index.html

代码示例如下:
package com.JavaMail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class MailServices {
Logger log = Logger.getLogger(MailServices.class.getName());

public void sendMail(String mailTitle, String receiveAddress,
String sendAddress, String userName, String password,
String serverSMTP) {
String title = mailTitle;
String serverSmtp = serverSMTP;// 10.3.7.10
try {
title = new String(title.getBytes("GBK"));
} catch (UnsupportedEncodingException e) {
log.error("邮件发送时出现异常", e);
}
Properties props = new Properties();
props.put("mail.smtp.host", serverSmtp);
props.put("mail.smtp.auth", "true");//不输出debug信息

Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息
Message message = new MimeMessage(mailSession);
try {
message.setFrom(new InternetAddress(sendAddress));//发件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
receiveAddress));// 收件人guo.yj@cppims.com
message.setSubject(title);//设置标题
message.setText(title);//邮件内容
message.saveChanges();
} catch (AddressException e) {
log.error("邮件地址配置有误!", e);
} catch (MessagingException e) {
log.error("邮件配置时出现异常!", e);
}
try {
Transport transport = mailSession.getTransport("smtp");
transport.connect(serverSmtp, userName, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
log.info("邮件发送成功!");
} catch (NoSuchProviderException e) {
log.error("邮件发送时出现异常!", e);
} catch (MessagingException e) {
log.error("邮件发送时出现异常!", e);
}

}

public static void main(String []args){
MailServices ms = new MailServices();
//ms.sendMail();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值