I am currently doing a project where I am required to send an email to the specific address taken from database. However, the column "email" in database does not actually contain emails, but names instead. So in database there are full names in russian language like
"Иванов Александр" which is "Ivanov Alexandr". So when I type this name in the outlook it automatically finds his email: AIvanov#domainname.com. But in my java code when I use name "Иванов Александр" i keep getting error.
Here is my java code
File[] listOfFiles = outDir.listFiles();
if (outDir.isDirectory()) {
if (outDir.list().length > 0) {
for (File file : listOfFiles) {
Session session_m = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session_m);
message.setFrom (new InternetAddress("mmm#domainname.com", "mmm#domainname.com"));
InternetAddress i = new InternetAddress("\""+email+"\"", false);
message.addRecipient(Message.RecipientType.TO, i);
message.setSubject("test");
message.setText("test");
message.setHeader("Content-Type","text/plain;charset=windows-1251");
MimeBodyPart mbp1 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
mbp1.setDataHandler(new DataHandler(fds));
mbp1.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
System.out.println("[EmailHandler] Attaching the following file to email: " + fds.getName());
message.setContent(mp);
SMTPTransport t = (SMTPTransport)session_m.getTransport("smtp");
t.connect("mail.domainname.com", "main#domainname.com", null);
System.out.println("[EmailHandler] Sending email... ");
t.sendMessage(message, message.getAllRecipients());
file.delete();
Thread.sleep(3000);
}
} else {
System.out.println("[EmailHandler] Folder " + outDir.getName() + " is empty... nothing to attach");
}
} else {
System.out.println("Folder not found... Check the path");
}
In this code the String email is Иванов Александр.
And I kept getting this error
javax.mail.internet.AddressException: Local address contains control or whitespace in string ``Иванов Александр''
So would like to know the ways I can make this string go through.
Thank you.
The outlook uses its address book to map a name to one of the email. That is why it is working fine, if you manually try creating a new email and just put the name. Outlook simply do a lookup in the address book and find out the email address.
However, this is not the same with a java program. The program needs exact email address to send an email. Now there could be many ways to find out email address.
The simplest approach is to store the email address in one of the database table.
If the person is associated with the company's SMTP system/active directory; you could use java smtp API / active directory APIs to find out the email or alias (usually be the part of email id before #) and then create email id to be used into the program to send email.
You need to provide a valid mail address. If you are using a fixed structure for your mails just convert the name to latin characters and append #domain.com
If you are not using any rules for your mail adress creation then I suggest you to add an email field to the database
Don't know if this resolves your question though
Regards
Your program have to
Validate e-mail.
It can be implemented using regular expression: Using a regular expression to validate an email address
Get email from contact list when field contains only name. There are two library for working with outlook contacts:
Open source java library to read outlook emails, calendar etc
Related
I am facing one problem while extracting BCC address from incoming mail.
Here is the sample code that is used.
public EmailVO dumpEnvelope(Message m) throws Exception {
EmailVO emailVO = new EmailVO();
if ((addresses = m.getRecipients(Message.RecipientType.BCC)) != null) {
emailVO.setBcc(this.getAddresses(addresses, "BCC"));
}
}
I am getting null value in BCC.
While debugging I found BCC recipient's name in header field but I am not able to access that header.
Is this code issue or there is some specific setting while sending mail like not to include BCC fields?
The whole point of Bcc is that it's a blind carbon copy - the recipients don't get to see who was copied. You won't see Bcc fields in messages you receive. (Sometimes a Bcc'ed recipient will see the Bcc header in the messages they receive, but the other recipients will get a copy of the message without the Bcc. But I don't think many mailers do that anymore because it requires sending two different versions of the message.)
You can check your Message object which contains all the details about the mails.
As the BCC is the part of mail but also it will be hidden, but as per my knowledge you can retrieve the information from your mail headers.
Address[] addresses = m.getHeader("Your Header Name HERE");
This will give you all the details regarding your particular header tag in mails.
for e.g.
Address[] addresses = m.getHeader("Delivered-To");
This tag will give you all the information about the recipients of the mail, which will also include BCC.
you can also add your custom headers for mail.
addresses = m.getRecipients(Message.RecipientType.BCC);
returns an array of addresses. You can check the content in a for loop:
Address[] addresses = m.getRecipients(Message.RecipientType.BCC);
for(Address address : addresses){
System.out.println(address);
}
i'm using java mail api to download java mail message attachment.
i am using this link tutorial
download mail attachment
but my requirement is that when user read mail it only display download link for attachment and when click on the link file downloaded that time.
Thanks
Manish
I think you want to do the following:
Check, if it is a multipart message AND consists of several parts
1.1 If so, it has attachments. You should then retrieve the first text/plain or text/html part, which should be the text itself. You leave the other parts alone. But along the text you store some id or reference to the message on the server, that the text is taken from. Consider the following code.
Folder folderInbox = store.getFolder("INBOX");
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
Message message = arrayMessages[i];
}
Now the class javax.mail.Message has a method getMessageNumber()::int.
If you store this message number and the folder name, in this case "INBOX",
you have an identifier, that will allow you to find the message on the server
again at a later time and do something with it, like downloading parts that have
not been retrieved yet.
So (pseudo code here) you basically have to do this.
var message_text = message.getFirstTextBodyPart();
var message_ident = (message.getFolderName(), message.getMessageNumber());
var message = (message_ident, message_text);
saveMessage(message);
showMessage(message);
1.2 In other cases, you download the entire message right now, as there are no parts for later retrieval.
An email is sent from lets say gg#gg.com with an attachment to 2 email id's .One, my email id and another xx#xx.com
I got that email. When i did mail search using java Mail API with email id as search criteria , it is not able to find it though i received that email.But when i forward it to the same email id's search criteria is working fine. Please let me know when email is received for the first time at that point why it is not able to search
Properties properties = System.getProperties();
properties.put("mail.smtp.host", ExchangeProperties.getSmtpHost());
properties.put("mail.pop3.connectiontimeout", String.valueOf(ExchangeProperties.getPop3ConnectionTimeout() * 1000));
properties.put("mail.pop3.timeout", String.valueOf(ExchangeProperties.getPop3Timeout() * 1000));
session = Session.getInstance(properties, null);
session.setDebug(logger.isDebugEnabled());
// Get the store
store = session.getStore("pop3");
store.connect(ExchangeProperties.getSmtpHost(), user, password);
Folder folder = store.getFolder(folderName)
Message[] foundMessages = folder.search(andTerm); //andTerm contains email id
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(foundMessages, fp);
Since you're using pop3, all the searching is done by downloading all the messages to the client and searching them there. If you want the server to do the searching, use imap.
If the new message arrives while you have the pop3 folder open, you won't be able to see it. You need to close the folder and reopen it. That's a limitation of the pop3 protocol.
If none of that helps with your problem, I would need to know exactly which search term you're using, exactly what value you're searching for, and exactly what value appears in the email header.
I am using Spring JavaMailSender for sending mail from our web-application. Until now it works great, except for this case: one of our customers reported that their email client can't read the characters in email, and show:
This message uses a character set that is not supported by the
Internet Service. To view the original message content, open the
attached message. If the text doesn't display correctly, save the
attachment to disk, and then open it using a viewer that can display
the original character set.
The strange thing is that only one person see this error. Others see the emails just fine. The troubled user is using Hotmail.
I searched through several forums, most of them are about frustrated customers about their email clients, but there's not many solutions/work arounds for server side. Some say that it's because of an in-the-way SMTP server doesn't support Unicode, but I don't think it's the case...
Here's my (simplified) code:
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(new InternetAddress("abc#abc.abc","Hoang Long"));
helper.setReplyTo("abc#abc.abc");
helper.setTo(student.getEmail());
helper.setSubject(emailSubject);
helper.setCc(studioParameterService.getAllCCEmailAddress(studio.getId()));
helper.setSentDate(new Date());
helper.setText(emailContent, true);
for (String filePath : attachFileList) {
FileSystemResource attachFile = new FileSystemResource(filePath);
helper.addAttachment(attachFile.getFilename(), attachFile);
}
mailSender.send(helper.getMimeMessage());
why mail content is sent as attachment when I send it to Hotmail account?
When I send mail to a Hotmail account the body of the mail is sent as attachment. But when sent to other accounts like yahoomail, gmail it is not creating any problem.
I want to know why I am getting problem with Hotmail accounts.
Please give me a solution for this.
MimeMessage msg = createMimeMessage(sender, emsg,session,mail.companyName); Transport.send(msg);
Multipart multipart = new MimeMultipart();
// This is the template Attachment part
if (emsg.getAttachment() != null) {
for (File file : emsg.getAttachment()) {
MimeBodyPart messageAttachmentBodyPart = new MimeBodyPart();
messageAttachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageAttachmentBodyPart.setDataHandler(new DataHandler(source));
messageAttachmentBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageAttachmentBodyPart);
}
}
Right. So, what happens if you send a file from a gmail account to a hotmail account, does it get attached? Or is it displayed just as you want? My guess is that attaching the file is a security measure to prevent malicious code from being activated on display. This mechanism might also be selective, meaning that it depends on the sender (an interesting post to read on this matter is this one).
Another thought: why is that a problem anyway?
Might help if you add
messageAttachmentBodyPart.setDisposition(Part.INLINE);