1.前提准备工作:
首先,邮件的发送方要开启POP3 和SMTP服务--即发送qq邮件的账号要开启POP3 和SMTP服务
2.开启方法:
登陆qq邮箱
3.点击 设置
4.点击—-账户
5.找到:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 —点击开启
6.送短信 —–点击确定
7.稍等一会,很得到一个授权码! –注意:这个一定要记住,一会用到
8.点击保存修改 —OK 完成
9.java 测试代码:
package cn.cupcat.test
import java.util.Properties
import javax.mail.Message
import javax.mail.MessagingException
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.AddressException
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMessage.RecipientType
public class SendmailUtil {
public static void main(String[] args) throws AddressException,MessagingException {
Properties properties = new Properties()
properties.put("mail.transport.protocol", "smtp")// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com")// 主机名
properties.put("mail.smtp.port", 465)// 端口号
properties.put("mail.smtp.auth", "true")
properties.put("mail.smtp.ssl.enable", "true")//设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true")//设置是否显示debug信息 true 会在控制台显示相关信息
//得到回话对象
Session session = Session.getInstance(properties)
// 获取邮件对象
Message message = new MimeMessage(session)
//设置发件人邮箱地址
message.setFrom(new InternetAddress("[email protected]"))
//设置收件人地址message.setRecipients(RecipientType.TO,new InternetAddress[] { new InternetAddress("[email protected]") })
//设置邮件标题
message.setSubject("这是第一封Java邮件")
//设置邮件内容
message.setText("内容为: 这是第一封java发送来的邮件。")
//得到邮差对象
Transport transport = session.getTransport()
//连接自己的邮箱账户
transport.connect("[email protected]", "vvctybgbvvophjcj")//密码为刚才得到的授权码
//发送邮件transport.sendMessage(message, message.getAllRecipients())
}
}
10.运行就会发出邮件了。。。。
下面是我收到邮件的截图,当然我把源码中的邮件地址都是修改了,不是真实的,你们测试的时候,可以修改能你们自己的邮箱。最后,祝你也能成功,如果有什么问题,可以一起讨论!
注意事项
得到的授权码一定要保存好,程序中要使用
建议方法:
如果你的java会死亡/失去控制, 请用系统的任务调度来发送邮件
如果你的java由jboss等之类的托管, 用jboss内部的任务调度来发送邮件.
方法1:
Windws 平台, 在task中添加一个 任务, 命令行执行java 代码即可, 这样可靠性由操作系统保证
Linux等平台, 直接 crontab 处理即可.
List<String> too=new ArrayList<String>()too.add("****@163.com")
// too.add("******@163.com")
InternetAddress[] to_mail = new InternetAddress[too.size()]
for (int i = 0 i < too.size() i++) { // 设置接收邮件人的地址
to_mail[i] = new InternetAddress(String.valueOf(too.get(i)))
}
messageHelper.setTo(to_mail)
不要用for循环 用internetAddress[] . 我前几天也是跟你一样.