qq邮箱格式的Java代码_Java实现QQ邮件发送

首先我们需要两个jar包,点击下面即可下载这两个包:

我们这里采用QQ邮箱发送邮件为例,代码如下:

0bf4226d1281c1fcfbc80aa394c52220.gif

package ddd;

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 com.sun.mail.util.MailSSLSocketFactory;

public class SendEmail {

public static void main(String[] args) {

try {

//设置发件人

String from = "xxx@qq.com";

//设置收件人

String to = "xxxx@qq.com";

//设置邮件发送的服务器,这里为QQ邮件服务器

String host = "smtp.qq.com";

//获取系统属性

Properties properties = System.getProperties();

//SSL加密

MailSSLSocketFactory sf = new MailSSLSocketFactory();

sf.setTrustAllHosts(true);

properties.put("mail.smtp.ssl.enable", "true");

properties.put("mail.smtp.ssl.socketFactory", sf);

//设置系统属性

properties.setProperty("mail.smtp.host", host);

properties.put("mail.smtp.auth", "true");

//获取发送邮件会话、获取第三方登录授权码

Session session = Session.getDefaultInstance(properties, new Authenticator() {

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(from, "第三方登录授权码");

}

});

Message message = new MimeMessage(session);

//防止邮件被当然垃圾邮件处理,披上Outlook的马甲

message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");

message.setFrom(new InternetAddress(from));

message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

//邮件标题

message.setSubject("This is the subject line!");

BodyPart bodyPart = new MimeBodyPart();

bodyPart.setText("我发送了文件给你");

Multipart multipart = new MimeMultipart();

multipart.addBodyPart(bodyPart);

//附件

bodyPart = new MimeBodyPart();

String fileName = "文件路径";

DataSource dataSource = new FileDataSource(fileName);

bodyPart.setDataHandler(new DataHandler(dataSource));

bodyPart.setFileName("文件显示的名称");

multipart.addBodyPart(bodyPart);

message.setContent(multipart);

Transport.send(message);

System.out.println("mail transports successfully");

} catch (Exception e) {

e.printStackTrace();

}

}

}

c526b6fc259e35057587dd485c56b3c9.gif

QQ邮箱发送邮件记得要在设置里面开启POP3/SMTP服务,然后获取第三方登录的授权码。

上面的代码中启用了SSL加密,网上很多人说QQ发送邮件不加上SSL加密会报错,楼主这里不加也是可以发送的不知道为什么,但是为了数据安全还是加上了。

有些人发送的邮件会被当做垃圾邮件处理,这里我也进行了处理,给邮件头披上Outlook的马甲,当然也可以将邮件内容以HTML格式发送,以防止被当成垃圾邮件。

上述就是一个简单的java发送QQ带附件的邮件的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值