2015-02-11 32 views
0

我複製了「quickstart:發送Gmail」中的代碼並修改了一些內容給我的應用程序。該代碼似乎工作正常,但發件人的名稱沒有得到設置,無論我如何嘗試它。在使用Gmail發送電子郵件時使用Java設置發件人姓名

這裏是我的完整代碼:

import java.util.Arrays; 
 
import java.util.Properties; 
 

 
import javax.mail.MessagingException; 
 
import javax.mail.Session; 
 
import javax.mail.internet.InternetAddress; 
 
import javax.mail.internet.MimeMessage; 
 

 
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 
 
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; 
 
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
 
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; 
 
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; 
 
import com.google.api.client.http.HttpTransport; 
 
import com.google.api.client.http.javanet.NetHttpTransport; 
 
import com.google.api.client.json.JsonFactory; 
 
import com.google.api.client.json.jackson.JacksonFactory; 
 
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64; 
 
import com.google.api.services.gmail.Gmail; 
 
import com.google.api.services.gmail.model.Message; 
 

 
public class Test{ 
 
\t private static final String SCOPE = "https://www.googleapis.com/auth/gmail.modify"; 
 
\t private static final String APP_NAME = "XYZ"; 
 
\t // Path to the client_secret.json file deloper Console 
 
\t private static final String CLIENT_SECRET_PATH = "src/testapp/auth_client.json"; 
 

 
\t private static GoogleClientSecrets clientSecrets; 
 
\t private static GoogleAuthorizationCodeFlow flow; 
 
\t private static HttpTransport httpTransport; 
 
\t private static JsonFactory jsonFactory; 
 
\t private static Gmail service; 
 

 
\t public static String getRequestUrl() throws FileNotFoundException, IOException{ 
 
\t \t httpTransport = new NetHttpTransport(); 
 
\t \t jsonFactory = new JacksonFactory(); 
 
\t \t 
 
\t \t clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(
 
\t \t \t \t CLIENT_SECRET_PATH)); 
 
\t \t 
 
\t \t // Allow user to authorize via url. 
 
\t \t flow = new GoogleAuthorizationCodeFlow.Builder(
 
\t \t \t \t httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE)) 
 
\t \t .setAccessType("online").setApprovalPrompt("auto").build(); 
 
\t \t 
 
\t \t String url = flow.newAuthorizationUrl() 
 
\t \t \t \t .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build(); 
 
\t \t 
 
\t \t return url; 
 
\t } 
 
\t 
 
\t public static void sendMail(String to, String sub, String body) throws IOException, MessagingException { 
 

 
\t \t Message message = createMessageWithEmail(createEmail(to, "me", sub, body)); 
 
\t  message = service.users().messages().send("me", message).execute(); 
 
\t  
 
\t  System.out.println("Message id: " + message.getId()); 
 
\t  System.out.println(message.toPrettyString()); 
 
\t } 
 

 
\t static void emailCredentialSetup(String code) throws IOException { 
 
\t \t // Generate Credential using retrieved code. 
 
\t \t GoogleTokenResponse response = flow.newTokenRequest(code) 
 
\t \t \t \t .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI) 
 
\t \t \t \t .execute(); 
 
\t \t GoogleCredential credential = new GoogleCredential() 
 
\t \t \t \t .setFromTokenResponse(response); 
 

 
\t \t // Create a new authorized Gmail API client 
 
\t \t service = new Gmail.Builder(httpTransport, jsonFactory, 
 
\t \t \t \t credential).setApplicationName(APP_NAME).build(); 
 
\t } 
 
\t 
 
\t /** 
 
\t * Create a MimeMessage using the parameters provided. 
 
\t * 
 
\t * @param to Email address of the receiver. 
 
\t * @param from Email address of the sender, the mailbox account. 
 
\t * @param subject Subject of the email. 
 
\t * @param bodyText Body text of the email. 
 
\t * @return MimeMessage to be used to send email. 
 
\t * @throws MessagingException 
 
\t * @throws UnsupportedEncodingException 
 
\t */ 
 
\t private static MimeMessage createEmail(String to, String from, String subject, 
 
\t  String bodyText) throws MessagingException, UnsupportedEncodingException { 
 
\t  Properties props = new Properties(); 
 
\t  Session session = Session.getDefaultInstance(props, null); 
 

 
\t  MimeMessage email = new MimeMessage(session); 
 

 
\t  email.setFrom(new InternetAddress(from, "SPecial message")); 
 
\t  email.addRecipient(javax.mail.Message.RecipientType.TO, 
 
\t      new InternetAddress(to)); 
 
\t  email.setSubject(subject); 
 
\t  email.setText(bodyText); 
 
\t  return email; 
 
\t } 
 
\t 
 
\t /** 
 
\t * Create a Message from an email 
 
\t * 
 
\t * @param email Email to be set to raw of message 
 
\t * @return Message containing base64 encoded email. 
 
\t * @throws IOException 
 
\t * @throws MessagingException 
 
\t */ 
 
\t private static Message createMessageWithEmail(MimeMessage email) 
 
\t  throws MessagingException, IOException { 
 
\t  ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
 
\t  email.writeTo(baos); 
 
\t  String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray()); 
 
\t  Message message = new Message(); 
 
\t  message.setRaw(encodedEmail); 
 
\t  return message; 
 
\t } 
 
\t 
 
\t public static void main(String[] args) throws FileNotFoundException, IOException, MessagingException { 
 
\t \t System.out.println(getRequestUrl()); 
 
\t \t BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
 
\t \t emailCredentialSetup(br.readLine()); 
 
\t \t 
 
\t \t sendMail("[email protected]", "TEST1", "Hello"); 
 
\t } 
 
}

有人可以幫我在發件人名稱設置爲自定義字符串?我嘗試了一些谷歌搜索後設置名稱爲「SPecial消息」,但它不起作用。

回答

0

似乎從你的代碼,你正在做的:

email.setFrom(new InternetAddress("me", "SPecial message")); 

這是試圖用「我」作爲電子郵件標題的電子郵件地址,這是行不通的。您需要將其設置爲用戶的真實電子郵件地址,或者不提供自動標題以自動設置。 (如果From標題中的電子郵件地址對用戶來說是錯誤的,它將刪除整個標題並設置一個有效標題。)

+0

謝謝你的回答@Eric DeFriez。我現在想用授權的用戶名替換「我」。因爲,我沒有直接從用戶那裏得到它,你如何建議我取回它? – 2015-03-06 10:54:50

+0

爲什麼不完全避免From頭?如果未提供,則Gmail API將爲用戶設置默認的一個,這可能是您想要的。 – 2015-03-06 17:06:32

+0

對於要求@Eric DeFriez的要求是正確的,但完全刪除From標題不會讓默認標題顯示出來。我評論過「email.setFrom(新的InternetAddress(來自」,「特權消息」));「在上面的代碼行和默認名稱正在顯示。 – 2015-03-08 13:22:14

0

從您的名字「特殊消息」中刪除空間嘗試發送這種方式「SpecialMessage」應該工作。

+0

不可以。這沒有用。 – 2015-02-11 20:08:35

+0

是什麼問題?它給了什麼錯誤? – sumitsabhnani 2015-02-12 03:52:31

+0

我想你將不得不在這裏做一些大的改變 url check:url: https://developers.google.com/admin-sdk/email-settings/?csw=1#creating_a_send-as_alias 檢查Java標籤爲此...您需要更改發送別名... – sumitsabhnani 2015-02-12 10:23:28

相關問題