Java Windows Automation-mail automatically send mail

Source: Internet
Author: User
Tags how to send mail

This article is designed to let testers know how to send mail


e-mail, the simplest thing is to send the mail directly, but in automated testing, should be done to let the machine or code to send mail automatically, I probably understand the following methods, there is always a taste for you:
1java code to do
The following is my Java code
Package util;
Import Javax.activation.DataHandler;
Import Javax.activation.FileDataSource;
Import javax.mail.*;
Import javax.mail.internet.*;
Import Java.io.File;
Import java.util.ArrayList;
Import Java.util.Date;
Import java.util.List;
Import java.util.Properties;

Import static Util.txt2.createArray;


public class mail{


/**
* @param args
* To for Send list, CC for cc list, BCC for secret send list, attach as attachment, username as useful user name, title for message title, txt for mail content
*/
public static final String user = "[email protected]";//Send mail Mailbox
public static final String pwd = "xxx";//Send mail mailbox password
public static final String SMTP = "smtp.exmail.qq.com";//Simple Mail Transfer Protocol
Static string[] to={"[email protected]", "[Email protected]"};
Static string[] cc={"[email protected]", "[Email protected]"};
Static string[] bcc={"[email protected]", "[Email protected]"};
Static string[] Bcc1=null;
Static final String attach = "e:\\work\\testauto_integration\\zlr.txt";//Attachment position
Static final String txt = "e:\\work\\testauto_integration\\zlr.txt";//Body position
Static String username = "XXX";
Static String title = "XXX";
public static void Main (string[] args) {
MAILZLR (tolist,mailname, "xxx", HOUR6);
}
public static void Mailzlr (string[] to,string[] cc,string attach,string username1,string title1,string txt)
{
MAILZLR (To,cc,bcc1,attach,username1,title1,txt);
}
public static void Mailzlr (string[] to,string attach,string username1,string title1,string txt)
{
MAILZLR (To,bcc1,bcc1,attach,username1,title1,txt);
}
public static void Mailzlr (string[] To, String username1, String title1, String txt)
{
MAILZLR (To,bcc1,bcc1,null,username1,title1,txt);
}
private static void Mailzlr (string[] to,string[] cc,string[] bcc,string attach,string username1,string title1,string txt )
{
File File1 = new file (TXT);
if (!file1.exists ())
{
Return
}
list<file> FileList = new arraylist<file> ();//Accessories list
if (attach!=null) {
File File = new file (attach);
Filelist.add (file);
}
String title =title1;
String username = username1;
String array[] = createarray (TXT);
String x=array[0]+ "\ n";
for (int i=1;i<array.length;i++)
{
x=x+array[i]+ "\ n";
}
String text = x+ "\ n" + "\ n";
try{
Properties props = System.getproperties ();
Props.put ("Mail.smtp.host", SMTP);//163 mailboxes are used by default here
Session session = NULL;
if (user! = null && pwd! = null) {
Props.put ("Mail.smtp.auth", "true");
Props.put ("Mail.smtp.user", user);
Props.put ("Mail.smtp.password", PWD);
} else {
Props.put ("Mail.smtp.auth", "false");
}
Session = Session.getinstance (props,
New Authenticator () {
Protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication (user, PWD);
}
});
MimeMessage message = new MimeMessage (session);
if (false) {//whether a receipt is required
Message.addheader ("Disposition-notification-to", "Receiving receipt address");
}
Message.setsubject (title);//
Message.setfrom (new internetaddress (user, username));
String toList = Getmaillist (To);
internetaddress[] iatolist = new InternetAddress (). Parse (toList);
Message.setrecipients (message.recipienttype.to,iatolist); Recipient
if (cc!=null) {
String toList1 = Getmaillist (cc);
internetaddress[] IaToList1 = new InternetAddress (). Parse (TOLIST1);
Message.setrecipients (Message.RecipientType.CC, iaToList1); CC person
}
if (bcc!=null) {
String toList2 = Getmaillist (BCC);
internetaddress[] IaToList2 = new InternetAddress (). Parse (TOLIST2);
Message.setrecipients (Message.RecipientType.BCC, iaToList2); Secret Delivery Person
}

Mimemultipart multi = new Mimemultipart ();
BodyPart Textbodypart = new MimeBodyPart ();

Textbodypart.settext (text);

Multi.addbodypart (Textbodypart);
if (FileList! = null) {
for (int i = 0; i < filelist.size (); i++) {
File f = (File) filelist.get (i);
F Iledatasource FDS = new Filedatasource (f);
BodyPart Filebodypart = new MimeBodyPart ();
Filebodypart.setdatahandler (New DataHandler (FDS));
Filebodypart.setfilename (Mimeutility.encodetext (F.getname ()));//If the attachment has Chinese through conversion no problem
Multi.addbodypart ( Filebodypart);
}
}
Message.setcontent (multi);
Message.setsentdate (New Date ());
Transport.send (message);
}catch (Exception e) {
E.printstacktrace ();
}
}
private static String getmaillist (string[] mailarray) {

StringBuffer toList = new StringBuffer ();
int length = Mailarray.length;
if (mailarray!=null && length <2) {
Tolist.append (Mailarray[0].replaceall ("!", "@"));
}else{
for (int i=0;i<length;i++) {
Tolist.append (Mailarray[i].replaceall ("!", "@"));
if (i!= (length-1)) {
Tolist.append (",");
}

}
}
return tolist.tostring ();

}
}

Here are a few parameters to note
Static string[] to={"[email protected]", "[Email protected]"}; This is the recipient of the message
Static string[] cc={"[email protected]", "[Email protected]"}; This is the CC of the message
Static string[] bcc={"[email protected]", "[Email protected]"}; This is the secret sender of the mail.
Attach is the attachment of the message, you need to specify a code on the machine path to send attachments, note that the folder, in essence, can not be sent, you need to switch to a compressed package and other ways to send
TXT is the body, you also need to specify a file, and attach the difference is that it needs to paste the content into the message body, so need to read the content, this article demonstrates the TXT
Username is the name of the sender of the message.
Title is the entire file header


2ant Mail label to implement the function of sending email


Ant allows us to use some keywords such as mail to send a message, but only allow to send a single file or compressed package as an attachment, and the body is only allowed to read from some documents
in the above described we will use ant to generate a report, inside a folder, But the folder is not sent out, want to send out must use the zip or tar and other keywords to the report folder
below to describe briefly

<tar destfile= "report.tar.bz" compression= "bzip2";
<fileset dir= "Report.zip";
<include Name= "*"/>
</fileset>
</tar>
<zip destfile= "Report.zip";
<zipfileset dir= " REPORT/${APPNAME}_ZLR_${MYDATE.DT4} "/>
</zip>
<!--ant Send mail configuration, supports multiple recipients, supports CC, sends messages in HTML format, Send Overview-summary.html as the main content-->
<mail from= "[email protected]" tolist= "[email protected]"
Cclist= "[email protected]" mailhost= "smtp.exmail.qq.com"
user= "[email protected]" password= "xxxx" subject= "Automated test Report (${date})"
messagefile= "${build.report.dir}/overview-summary.html"
messagemimetype= "text /html "
<attachments>
<fileset dir="/home/work/zouleiran/apache-ant-1.9.4/bin/autotest ">
<include name= "Report.zip"/>
</fileset>
</attachments>
</mail>

The key points:
The TAR keyword indicates that the tar package, where Fileset dir is the path to the folder to be packaged, contains the following * means that all files in that folder are packaged, similar to Linux *
Zip keyword means zip package, similar to tar

The following mail keyword is a mail message that can be used in analogy with code
From is the sender of the mail, fill in the email to send the classmate's mailbox
ToList is sent to the list of people, the middle can be used, spaces
CCList is a copy to the list of people, the middle can be used, space
Mailhost for the mailbox agreement, 163 and Teng Xun Enterprise mailbox is this, the rest may not be the same, to specific problems specific analysis
User and password are message headers
Messagefile and Messagemimetype is the text, the text is shown in TXT format or HTML format, theoretically OK, but the author only used the two, the general this OK
Attachments tag is an attachment, no can not write, as above packaging, indicate the file path and the file to be sent, as an attachment to send out

3 request mail server directly to send mail
For large companies, for the following reasons
A automatic e-mail message demand is relatively large, it is necessary to build a server
b People who use this technology are uneven, not even technical, and need a simpler and more unified way to automatically email or mail-push
C-Pack X
D Company mailbox protocol is more complex, even passwords are 1 minutes a change of random passwords, the security of strong use of low, so this way will be relatively concise
So large companies generally have multiple mail systems, not even code to do, users only need to click on the page, this situation is not discussed in this article


4ui Automation
Frankly speaking, the general mailbox is able to log on the Web, and if the UI Automation skilled that is not a problem, the page click to send the message, but then back, if the UI Automation to understand the kind of people who can automatically send e-mail, how can not write the code of mail?
According to my actual work experience, this situation is mainly used in the following scenarios:
1 page no verification code
2 Mailbox protocol complex, how can not be adjusted, and there is no company unified mailbox Sending server
3 pack X

5jmeter sending mail
This article does not introduce too much, only need to understand, because ant contains jmeter keyword tags, make it possible to send mail with the help of JMeter, but the above method will feel jmeter email rather troublesome, extremely not recommended

The above is a brief introduction to the method of sending e-mail, using Java to send e-mail is basically three ways, then how are they different?

Send mail using the company's Unified mailbox Service
Apply to the confidentiality of the company employees, especially the company's mailbox protocol and password, there are many special, not easy to use the code to send

When we do automation in small companies or send mail, the two most common ways
1 sending messages using Java code
Requires a bit of code capability, and the benefit is the ability to send email anytime, anywhere, rather than being too limited by ant tools
2 using ant to send mail
There's actually a certain code capability here, but it's lower, but because using ant to send mail makes us vulnerable to ant's limitations.
There are a number of restrictions on the timing of sending emails, the contents of sending emails, the format of messages, and so on.

Therefore, I recommend the use of code to send mail

Java Windows Automation-mail automatically send mail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.