对于代发邮件我们经常见于注册验证,服务通知等,在这里我们用Java和Python实现邮件发送。在Java中需要导入包mail.jar.
以下是使用Java的方法:
首先创建setMessage类用来构造邮件发送的内容,包括主题、正文、附件。实现代码如下:
首先创建setMessage类用来构造邮件发送的内容,包括主题、正文、附件。实现代码如下:
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class setMessage{
private String from_mail;
private String to_mail;
private String subject;
private String text;
private String filePath;
setMessage(String fmail,String tomail,String subt,String txt,String fPath)
{
from_mail=fmail;
to_mail=tomail;
subject=subt;
text=txt;
filePath=fPath;
}
/**
* 根据文件绝对路径创建附件如"F:\\music\\kiss.mp3"
*/
public MimeBodyPart createAttachment(String filePath) throws Exception {
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(filePath);
attachmentPart.setDataHandler(new DataHandler(fds));
attachmentPart.setFileName(fds.getName());
return attachmentPart;
}
/**
* 根据字符创建邮件正文部分
*/
public MimeBodyPart createContent(String body) throws Exception{
MimeBodyPart contentBody = new MimeBodyPart();
/*用于组合文本和图片,"related"型的MimeMultipart对象*/
MimeMultipart contentMulti = new MimeMultipart("related");
MimeBodyPart textBody = new MimeBodyPart();
textBody.setContent(body, "text/html;charset=gb2312");
contentMulti.addBodyPart(textBody);
contentBody.setContent(contentMulti);
return contentBody;
}
/**
* 根据传入的 Seesion对象创建消息
*/
public MimeMessage createMessage(Session session) throws Exception{
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from_mail));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to_mail));
msg.setSubject(subject);
MimeBodyPart content = createContent(text);
/*将邮件中各个部分组合成MimeMultipart 对象*/
MimeMultipart allPart = new MimeMultipart();
if(filePath!="")
{
MimeBodyPart att = createAttachment(filePath);
allPart.addBodyPart(att);
}
allPart.addBodyPart(content);
/* 将MimeMultipart 对象作为邮件内容并保存*/
msg.setContent(allPart);
msg.saveChanges();
return msg;
}
}
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class MessageSender {
String smtpServer="smtp.";
String user;
String pswd;
MessageSender(String user,String pswd){
this.user=user;
this.pswd=pswd;
setSmtp();
}
void setSmtp(){
String temp=user;
temp=temp.substring(temp.indexOf('@')+1, temp.length());
smtpServer+=temp;
}
public String getuser(){
return user;
}
/**
* 创建Session对象,配置传输的协议,设置需要身份认证
*/
public Session createSession(String protocol) {
Properties property = new Properties();
property.setProperty("mail.transport.protocol", protocol);
property.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(property);
/*启动调试功能,可以从控制台中读取服务器的响应信息,这里我将其设为关闭 */
session.setDebug(false);
return session;
}
/**
* 传入Session、MimeMessage对象,创建 Transport对象发送邮件
*/
public void sendMail(Session session, MimeMessage msg) throws Exception {
/*由 Session对象获得Transport对象*/
Transport transport = session.getTransport();
/*发送用户名、密码连接到指定的 smtp服务器*/
transport.connect(smtpServer, user, pswd);
transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
transport.close();
}
public static void main(String[] args) throws Exception {
String from_ml,to_ml,subjet,txt,fpath;
/*以发件人的账号和密码为参数创建sender对象*/
MessageSender sender=new MessageSender("xxxxxxx@xx.com","*******");
/*使用SMTP协议来创建Session对象*/
Session session = sender.createSession("smtp");
/*收发地址、主题、正文、附件路径*/
from_ml=sender.getuser();
to_ml="xxxxxxxx@xx.com";
subjet="Test mail";
txt="This is a test mail";
fpath="";
MimeMessage mail = new setMessage(from_ml,to_ml,subjet,txt,fpath).createMessage(session);
sender.sendMail(session, mail);
}
}
Python方法:
import smtplib
from email.mime.text import MIMEText
tomail_list=["xxxxxx@xx.com"] #inbox list
mail_host="smtp.xx.com" #set server
mail_user="xxxxxxx@xx.com" #your account
mail_pass="*******" #your password
mail_postfix="xx.com" #outbox suffix
def send_mail(to_list,sub,content):
me="Holif"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__=='__main__':
if send_mail(tomail_list,"test mail","This is a test mail,Please don't reply!"):
print "success"
else:
print "failed"