




已阅读5页,还剩6页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Matlab发送html格式邮件Matlab是非常优秀的数据分析软件,具有很多优秀的功能,比如发送邮件。但是matlab自带的sendmail不支持html方式发送邮件正文,有时候非常不方便。查询可知matlab的sendmail和java的javax.mail package有密切关系,可以通过修改原函数的部分参数,扩展后就可以发送带html格式正文的邮件了。先截图看下效果:修改的部分为:将原函数的119-130行改为下图所示:修改前修改后此外将maxLineLength = 75;改为maxLineLength = inf;然后再按照原来函数的用法发送邮件就可以了。做法来源于:/blog/sending-html-emails-from-matlab。附件自带本人修改后的函数,可以复制下到matlab创建函数直接使用。注意:使用sendmail函数发送邮件之前需要先进行设置,具体可以参考matlab说明。function sendmail(to,subject,theMessage,attachments)%SENDMAIL Send e-mail.% SENDMAIL(TO,SUBJECT,MESSAGE,ATTACHMENTS) sends an e-mail. TO is either a% character vector specifying a single address, or a cell array of character vector% addresses. SUBJECT is a character vector. MESSAGE is either a character vector or a cell% array of character vectors. If it is a character vector, the text will% automatically wrap at 75 characters. If it is a cell array, it wont wrap, but% each cell starts a new line. In either case, use char(10) to explicitly specify% a new line. ATTACHMENTS is a character vector or a cell array of character% vectors listing files to send along with the message. Only TO and SUBJECT are% required.% SENDMAIL relies on two preferences, Internet:SMTP_Server, your mail server, and% Internet:E_mail, your e-mail address. Use SETPREF to set these before using% SENDMAIL. The easiest ways to identify your outgoing mail server is to look at% the preferences of another e-mail application or consult your administrator. If% you cannot find out your servers name, setting it to just mail might work. If% you do not set these preferences SENDMAIL will try to determine them% automatically by reading environment variables and the Windows registry.% Example:% setpref(Internet,SMTP_Server,);% setpref(Internet,E_mail,);% sendmail(,Calculation complete.)% sendmail(,,Youre cool!, .% See the attached files for more info.,attach1.m,d:attach2.doc);% sendmail(,Adding additional breaks,one 10 two);% sendmail(,Specifying exact lines,one,two);% See also WEB, FTP.% Copyright 1984-2016 The MathWorks, Inc.% This function requires Java.if usejava(jvm) error(message(MATLAB:sendmail:NoJvm);endimport javax.mail.*import ernet.*import javax.activation.*% Argument parsing.narginchk(2,4);if ischar(to) to = to;endif (nargin 3) theMessage = ;endif (nargin 4) attachments = ;elseif ischar(attachments) attachments = attachments;end% Determine server and from.server,from = getServerAndFrom;if isempty(server) commandStr = setpref(Internet,SMTP_Server,); error(message(MATLAB:sendmail:SMTPServerIndeterminate,commandStr);endif isempty(from) commandStr = setpref(Internet,E_mail,); error(message(MATLAB:sendmail:FromAddressIndeterminate,commandStr);end% Use the system properties, but clone them so we dont alter ps = java.lang.System.getProperties.clone;props.put(mail.smtp.host,server);% Create session.username = getpref(Internet,SMTP_Username,);password = getpref(Internet,SMTP_Password,);if isempty(username) pa = ;else pa = com.mathworks.util.PasswordAuthenticator(username,password);endsession = Session.getInstance(props,pa);% Create the theMessage.msg = MimeMessage(session);% Set sender.msg.setFrom(getInternetAddress(from);% Set recipients.for i = 1:numel(to) msg.addRecipient(getRecipientTypeTo(msg), . getInternetAddress(toi);end% Try to do the right thing on Japanese machines.isJapanese = ispc & strncmpi(ernal.display.language,ja,2);% If charset is specified in preferences, then use itcharset = ;if ispref(Internet, E_mail_Charset) charset = getpref(Internet, E_mail_Charset); elseif isJapanese charset = UTF-8;end% Set subject.if any(subject = char(10) | any(subject = char(13) error(message(MATLAB:sendmail:InvalidSubject);endif isempty(charset) msg.setSubject(subject, charset)else msg.setSubject(subject)end% Set other headers.msg.setHeader(X-Mailer, MATLAB version)msg.setSentDate(java.util.Date);% Construct the body of the message and attachments.body = formatText(theMessage);isHtml = isempty(body) & body(1) = ; % msg starting with indicates HTMLif isHtml if isempty(charset) charset = text/html; charset=utf-8; else charset = text/html; charset= charset; endendif numel(attachments) = 0 & isHtml if isHtml msg.setContent(body, charset); elseif isempty(charset) msg.setText(body, charset); else msg.setText(body); endelse % Add body text. messageBodyPart = MimeBodyPart; if isHtml messageBodyPart.setContent(body, charset); elseif isempty(charset) messageBodyPart.setText(body, charset); else messageBodyPart.setText(body); end multipart = MimeMultipart; multipart.addBodyPart(messageBodyPart); % Add attachments. for iAttachments = 1:numel(attachments) file = attachmentsiAttachments; messageBodyPart = MimeBodyPart; fullName = locateFile(file); if isempty(fullName) error(message(MATLAB:sendmail:CannotOpenFile, file); end source = FileDataSource(fullName); messageBodyPart.setDataHandler(DataHandler(source); % Remove the directory, if any, from the attachment name. , fileName, fileExt = fileparts(fullName); messageBodyPart.setFileName(fileName fileExt); multipart.addBodyPart(messageBodyPart); end % Put parts in message msg.setContent(multipart);end% Send the message.try Transport.send(msg);catch exception % Try to make the Java error friendlier. niceError = stripJavaError(exception.message); if isempty(niceError) throw(exception); else error(message(MATLAB:sendmail:SmtpError, niceError) endend%=function server,from = getServerAndFrom%getServerAndFrom Look in several places for default values.% Check preferences.server = getpref(Internet,SMTP_Server,);from = getpref(Internet,E_mail,);% Check Java properties.if isempty(server) props = java.lang.System.getProperties; server = char(props.getProperty(mail.smtp.host);end% Determine defaultMailAccountRegistry.if (ispc & (isempty(server) | isempty(from) try defaultMailAccount = winqueryreg(HKEY_CURRENT_USER, . SoftwareMicrosoftInternet Account Manager, . Default Mail Account); defaultMailAccountRegistry = . SoftwareMicrosoftInternet Account ManagerAccounts . defaultMailAccount; catch exception %#ok defaultMailAccountRegistry = ; endend% Determine SERVERif ispc & isempty(server) & isempty(defaultMailAccountRegistry) try server = winqueryreg(HKEY_CURRENT_USER,defaultMailAccountRegistry, . SMTP Server); catch exception %#ok endendif isempty(server) server = getenv(MAILHOST);end% Determine FROMif ispc & isempty(from) try from = winqueryreg(HKEY_CURRENT_USER,defaultMailAccountRegistry, . SMTP Email Address); catch exception %#ok endendif isempty(from) from = getenv(LOGNAME);end%=function internetAddress = getInternetAddress(from)%getInternetAddress Instantiate an InternetAddress object.try internetAddress = ernet.InternetAddress(from);catch exception error(message(MATLAB:sendmail:AddressError, stripJavaError( exception.message );end%=function recipientTypeTo = getRecipientTypeTo(msg)%getRecipientTypeTo Return the static RecipientType.TO.% Get the class loader for the Message class.cl = msg.getClass.getClassLoader;% Returns a Class object pointing to RecipientType using that ClassLoader.rt = java.lang.Class.forName(javax.mail.Message$RecipientType, false, cl);% Returns a Field object pointint to TO.field = rt.getField(TO);% Gets the static instance of TO.recipientTypeTo = field.get();%=function fullPathToFile = locateFile(file)%LOCATEFILE Resolve a filename to an absolute location.% LOCATEFILE(FILE) returns the absolute path to FILE. If FILE cannot be% found, it returns an empty string.% Matthew J. Simoneau, November 2003% Checking that the length is exactly one in the first two checks automatically% excludes directories, since directory listings always include . and .if (length(dir(fullfile(pwd,file) = 1) % Relative path. fullPathToFile = fullfile(pwd,file);elseif (length(dir(file) = 1) % Absolute path. fullPathToFile = file;elseif isempty(rospective.safeWhich(file) % A file on the path. fullPathToFile = rospective.safeWhich(file);elseif isempty(rospective.safeWhich(file .) % A file on the path without extension. fullPathToFile = rospective.safeWhich(file .);else fullPathToFile = ;end%=function toSend = formatText(msgText)%formatText Format a block of text, adding line breaks every chars.cr = char(10);% For a cell array, send each cell as one line.if iscell(msgText) toSend = strjoin(reshape(msgText, 1, numel(msgText),cr); returnend% For a char array, break each line at a char(10) or try to wrap to 75 % characters.lines = ;maxLineLength = inf;msgText = cr msgText cr;crList = find(msgText = cr);for i = 1:length(crList)-1 nextLine = msgText(crList(i)+1 : crList(i+1)-1); lineLength = length(nextLine); nextStart = 1; moreOnLine = true; while moreOnLine start = nextStart; if (lineLength-start+1 = start); nonSpaces = find(nextLine = ); nonSpaces = nonSpaces(nonSpaces = start); if isempty(spaces)% % No spaces anywhere. Chop!% stop = start+maxLineLength-1; % No spaces anywhere. Preserve. stop = lineLength; elseif isempty(nonSpaces) % Nothing but spaces. Send an empty line. stop = start-1; elseif (min(spaces) (start+maxLineLength)% % The first space doesnt show up soon enough to help. Chop!% stop = start+maxLineLength-1; % No spaces anywhere. Preserve. stop = lineLength; elseif isempty(spaces( . spaces min(nonSpaces) & spaces start+maxLineLength . )% % There are only leading spaces, which we respect. Chop!% stop = start+maxLineLength-1; % No space
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年事业单位工勤技能-湖南-湖南垃圾清扫与处理工一级(高级技师)历年参考题库含答案解析
- 2025年事业单位工勤技能-湖北-湖北家禽饲养员三级(高级工)历年参考题库含答案解析
- 工业互联网平台漏洞扫描技术在金融行业的风险防控报告
- 2025-2030中国端氨基聚醚行业应用趋势及竞争格局预测报告
- 2025年事业单位工勤技能-河北-河北计算机文字录入处理员一级(高级技师)历年参考题库含答案解析(5套)
- 2025年事业单位工勤技能-河北-河北堤灌维护工二级(技师)历年参考题库含答案解析
- 2025年事业单位工勤技能-河北-河北假肢制作装配工一级(高级技师)历年参考题库含答案解析
- 2025年事业单位工勤技能-江西-江西殡葬服务工二级(技师)历年参考题库含答案解析(5套)
- 2025年事业单位工勤技能-广西-广西理疗技术员四级(中级工)历年参考题库典型考点含答案解析
- 2025年事业单位工勤技能-广西-广西堤灌维护工三级(高级工)历年参考题库典型考点含答案解析
- (2025年标准)委托他人要账协议书
- 2025-2030中国青少年无人机教育课程体系构建与创新能力培养研究
- 煤矿安全规程新旧版本对照表格版
- 2025山东“才聚齐鲁成就未来”水发集团高校毕业招聘241人笔试参考题库附带答案详解(10套)
- 中学2025年秋季第一学期开学工作方案
- 儿童急救流程
- GB 11122-2025柴油机油
- 私募薪酬管理办法
- 经营废钢管理办法
- 药品经营企业讲课课件
- 广东省深圳市海韵中学2026届中考押题语文预测卷含解析
评论
0/150
提交评论