Java:
首先要先下载mail.jar。链接:点击打开链接
public class MailUtil {
public final static String EMAIL_FORM="abcd@163.com";
public final static String EMAIL_HOST="smtp.163.com";
public final static String EMAIL_USERNAME="abcd@163.com";
public final static String EMAIL_PWD="";
public static void sendMail(String toEmail, String subject, String content) {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
// 发送邮箱的邮件服务器
senderImpl.setHost(EMAIL_HOST);
// 建立邮件消息,发送简单邮件和html邮件的区别
MimeMessage mailMessage = senderImpl.createMimeMessage();
// 为防止乱码,添加编码集设置
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, "UTF-8");
try {
// 接收方邮箱
messageHelper.setTo(toEmail);
} catch (MessagingException e) {
throw new RuntimeException("收件人邮箱地址出错!");
}
try {
// 发送方邮箱
messageHelper.setFrom(EMAIL_FORM);
} catch (MessagingException e) {
throw new RuntimeException("发件人邮箱地址出错!");
}
try {
messageHelper.setSubject(subject);
} catch (MessagingException e) {
throw new RuntimeException("邮件主题出错!");
}
try {
// true 表示启动HTML格式的邮件
messageHelper.setText(content, true);
} catch (MessagingException e) {
throw new RuntimeException("邮件内容出错!");
}
Properties prop = new Properties();
// 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
prop.put("mail.smtp.auth", "true");
// 超时时间
prop.put("mail.smtp.timeout", "25000");
// 添加验证
MyAuthenticator auth = new MyAuthenticator(EMAIL_USERNAME,EMAIL_PWD);
Session session = Session.getDefaultInstance(prop, auth);
senderImpl.setSession(session);
// senderImpl.setJavaMailProperties(prop);
// 发送邮件
senderImpl.send(mailMessage);
}
}
public class MyAuthenticator extends Authenticator {
private String username;
private String password;
/**
* @param username
* @param password
*/
public MyAuthenticator(String username, String password) {
super();
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
注意事项:密码为stmp服务的授权码,而不是邮箱的登录密码。
使用Python:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = 'a@163.com'
receiver = ['1@qq.com']
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式
message = MIMEText('Python 邮件发送测试...', _subtype='plain')
message['From'] = Header("<a@163.com>") # 发送者
message['To'] = Header(receiver[0]) # 接收者
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect("smtp.163.com")
smtpObj.login("a","1234") #用户名与密码
smtpObj.sendmail(sender, receiver, message.as_string())
smtpObj.close()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")